Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the difference of two querysets in Django?

I have to querysets. alllists and subscriptionlists

alllists = List.objects.filter(datamode = 'A') subscriptionlists = Membership.objects.filter(member__id=memberid, datamode='A') 

I need a queryset called unsubscriptionlist, which possess all records in alllists except the records in subscription lists. How to achieve this?

like image 458
Rajasekar Avatar asked May 10 '11 06:05

Rajasekar


People also ask

How do I join two Querysets in Django?

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function. Instead of itertools.

What does .values do in Django?

Return Specific Columns The values_list() method allows you to return only the columns that you specify.

How do I merge two Django models?

1 Answer. Show activity on this post. In your models Device and History models are related with a foreign key from History to DeviceModel, this mean when you have a History object you can retrieve the Device model related to it, and viceversa (if you have a Device you can get its History).

What is double underscore in Django?

The double underscore notation is used by Django's ORM to indicate some sort of separation in a query. In the case of tr_rowid_debtor__de_listed_date__lte , three things are happening. tr_rowid_debtor specifies the attribute on DeTransaction , which is a relationship based on what happens next.


2 Answers

Since Django 1.11, QuerySets have a difference() method amongst other new methods:

# Capture elements that are in qs_all but not in qs_part qs_diff = qs_all.difference(qs_part)     

Also see: https://stackoverflow.com/a/45651267/5497962

like image 174
markus-hinsche Avatar answered Oct 11 '22 13:10

markus-hinsche


You should be able to use the set operation difference to help:

set(alllists).difference(set(subscriptionlists)) 
like image 28
Brian Fisher Avatar answered Oct 11 '22 14:10

Brian Fisher