本文介绍了简单的Djanqo查询产生令人困惑的Queryset结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[更新:软件版本Python 2.7.2,Django 1.3.1]



任何人都可以解释这个控制台代码? >

FinishingStep对引用对象有一个ForeignKey,但并不真正相关。

 >>> fin = FinishingStep.objects.filter(quote = jq)
>>> fin
[< FinishingStep:Tabbing>< FinishingStep:Collat​​or>]

非常好,我们已经返回了一个具有两个对象的QuerySet。



但是现在的混乱。这两个对象现在看起来都是一样的:

 >>> fin [0] 
< FinishingStep:Collat​​or>
>>> fin [1]
< FinishingStep:Collat​​or>

将其转换为列表,并修复它。

 >>> fin = list(fin)
>>>> fin
[< FinishingStep:Tabbing>< FinishingStep:Collat​​or>]
>>> fin [0]
< FinishingStep:Tabbing>
>>> fin [1]
< FinishingStep:Collat​​or>

[更新:将.distinct()添加到查询中也会修复它。这个特别奇怪的是,目前在数据库中只有这两个项目。]



这是一个bug吗?我做错了什么?

解决方案

这个机票讨论了这个行为:



只需使用 order_by 查询。这是因为数据库引擎可以自由返回任何合适的行,如果您没有指定明确的排序。所以我想它只是从缓存中挑选一个。


[Update: software versions Python 2.7.2, Django 1.3.1]

Can anyone explain this console code?

FinishingStep has a ForeignKey to a quote object, but that's not really relevant.

>>> fins = FinishingStep.objects.filter(quote=jq)
>>> fins
[<FinishingStep: Tabbing>, <FinishingStep: Collator>]

So far so good, we have returned a QuerySet with two objects.

But now the confusion. Both objects now appear to be the same:

>>> fins[0]
<FinishingStep: Collator>
>>> fins[1]
<FinishingStep: Collator>

Convert it to a list, and that fixes it.

>>> fins = list(fins)
>>> fins
[<FinishingStep: Tabbing>, <FinishingStep: Collator>]
>>> fins[0]
<FinishingStep: Tabbing>
>>> fins[1]
<FinishingStep: Collator>

[Update: Adding .distinct() to the query also fixes it. This especially odd since, at the moment, there are only those two items in the database.]

Is this a bug? Am I doing something wrong?

解决方案

This ticket discusses this behavior: https://code.djangoproject.com/ticket/9006

Just use order_by query. This happens because the database engine is free to return any suitable row if you do not specify explicit ordering. So I guess it just picks the one from its cache.

这篇关于简单的Djanqo查询产生令人困惑的Queryset结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 12:21