Django – combine two querysets

I had to get a list of accounts that either had some activity going around. Activity could be varying, e.g. has active deployments or quotes being exchanged, and therefore getting data from two different models. Here’s how I managed to merge the querysets together:

from itertools import chain
from django.db.models import Q

active_deal_accounts = Deal.objects.filter('account_id').distinct()
active_installation_accounts = Installation.objects.filter(Q(|
active_deal_results = Account.objects.filter(id__in=active_deal_accounts)
active_installation_results = Account.objects.filter(id__in=active_installation_accounts)
results = list(chain(active_deal_results, active_installation_results))

More info on StackOverflow article


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s