I've observed this behavior and I don't quite understand. Let say I make a query:
result = model.objects.all()
result_pks = result.values_list("id",flat=True)
print result_pks
And I get:
[1,2,3,4]
Then I want to check if a certain value is in the list of pks returned:
val = 2
print val in result_pks
This will return True, but if instead I change result to:
result = model.objects.prefetch_related("related_field").all()
result_pks = result.values_list("id",flat=True)
print result_pks
I still get:
[1,2,3,4]
But when I do:
val=2
print val in result_pks
I get False. I tried using select_related instead, and that returned True as I expected. Can someone explain to me why the difference?
In terms of performance, there is no difference between values() and values_list().
Django provides a count() method for precisely this reason. Note: If you only want to determine if at least one result exists (and don't need the actual objects), it's more efficient to use exists() .
Are you using Django 1.5?
There was a bug that caused the in
lookup to fail when using prefetch_related
: bug 20242.
This has been fixed in Django 1.6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With