Comparing QuerySets

289 views
Skip to first unread message

Thomas Guettler

unread,
Apr 5, 2012, 5:07:42 AM4/5/12
to Django users
I was surprised, that comparing querysets does not work:

{{{
from django.contrib.auth.models import User
user_id=User.objects.all().order_by('id')[0].id

if not User.objects.filter(id=user_id)==User.objects.filter(id=user_id):
print 'Not equal? I think they should be'

ids1=User.objects.filter(id=user_id).values_list('id', flat=True)
ids2=User.objects.filter(id=user_id).values_list('id', flat=True)
if not ids1==ids2:
print 'Not equal? I think they should be: %s %s' % (ids1, ids2)

}}}

Both, django 1.3 and 1.4 print this result:
Not equal? I think they should be
Not equal? I think they should be: [1] [1]

I could not find a documentation of this in the django docs[1].

Before creating a doc-ticket I want to ask here.

[1] https://docs.djangoproject.com/en/dev/ref/models/querysets/

--
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de

Andre Terra

unread,
Apr 5, 2012, 12:21:59 PM4/5/12
to django...@googlegroups.com
Not sure if this is efficient, but you can try wrapping the values_list in a set() call.

>>> set(ids1) == set(ids2)

True

>>> set(ids1) & set(ids2)

set([1])

>>> ids3 = set([])

>>> r = set(ids1) & set(ids3)

>>> r

set([])

>>> len(r)

0



Cheers,
AT

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.


Reply all
Reply to author
Forward
0 new messages