问题
[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?
回答1:
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.
来源:https://stackoverflow.com/questions/7843687/simple-djanqo-query-generating-confusing-queryset-results