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(support_end__gte=datetime.datetime.now()).values('account_id').distinct()
active_installation_accounts = Installation.objects.filter(Q(support_expires__gte=datetime.datetime.now())|
    Q(support_extension__gte=datetime.datetime.now())).values('account_id').distinct()
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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s