简单的 Djanqo 查询生成令人困惑的查询集结果
[更新:软件版本Python 2.7.2、Django 1.3.1]
谁能解释一下这个控制台代码?
FinishingStep 有一个引用对象的外键,但这并不真正相关。
>>> fins = FinishingStep.objects.filter(quote=jq)
>>> fins
[<FinishingStep: Tabbing>, <FinishingStep: Collator>]
到目前为止一切顺利,我们返回了一个包含两个对象的 QuerySet。
但现在混乱了。两个对象现在看起来是相同的:
>>> fins[0]
<FinishingStep: Collator>
>>> fins[1]
<FinishingStep: Collator>
将其转换为列表,然后修复它。
>>> fins = list(fins)
>>> fins
[<FinishingStep: Tabbing>, <FinishingStep: Collator>]
>>> fins[0]
<FinishingStep: Tabbing>
>>> fins[1]
<FinishingStep: Collator>
[更新:将 .distinct() 添加到查询中也可以修复该问题。这特别奇怪,因为目前数据库中只有这两项。]
这是一个错误吗?我做错了什么吗?
[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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此票证讨论了此行为: https://code.djangoproject.com/ticket/9006
只需使用
order_by
查询。发生这种情况是因为如果您不指定显式排序,数据库引擎可以自由返回任何合适的行。所以我猜它只是从缓存中选择一个。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.