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

时间:2022-04-20 01:35:18

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:

然后我想检查返回的pks列表中是否有某个值:

val = 2
print val in result_pks

This will return True, but if instead I change result to:

这将返回True,但如果相反,我将结果更改为:

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?

我弄错了。我尝试使用select_related,并按预期返回True。有人可以向我解释为什么会有区别吗?

1 个解决方案

#1


7  

Are you using Django 1.5?

你在使用Django 1.5吗?

There was a bug that caused the in lookup to fail when using prefetch_related: bug 20242.

使用prefetch_related时,有一个错误导致查找失败:错误20242。

This has been fixed in Django 1.6.

这已在Django 1.6中修复。

#1


7  

Are you using Django 1.5?

你在使用Django 1.5吗?

There was a bug that caused the in lookup to fail when using prefetch_related: bug 20242.

使用prefetch_related时,有一个错误导致查找失败:错误20242。

This has been fixed in Django 1.6.

这已在Django 1.6中修复。