Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: check if value in values_list with & without prefetch_related/select_related

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?

like image 847
CoffeeJack Avatar asked Nov 14 '13 20:11

CoffeeJack


People also ask

What is the difference between values and values_list in Django?

In terms of performance, there is no difference between values() and values_list().

How do you check is exists in Django?

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() .


1 Answers

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.

like image 184
Simeon Visser Avatar answered Dec 10 '22 19:12

Simeon Visser