我试图了解 values() 和 annotate() 的工作原理。
在我的应用程序中,我有一个模型
class MyEntry(models.Model):
entrydate = models.DateField(default=date.today)
...
如果我在 python shell 中执行以下操作
>>allentries = MyEntry.objects.all()
>>vals = allentries.values('entrydate')
>>vals[:2]
[{ 'entrydate':datetime.date(2013,2,24)},
{ 'entrydate':datetime.date(2013,2,8)}]
那么,如果我应用注释
>>valsannot = vals.annotate(dailycount=Count('entrydate'))
>>valsannot[:2]
[{ 'entrydate':datetime.date(2013,2,24),'dailycount':1},
{ 'entrydate':datetime.date(2013,2,8)},'dailycount':2]
当我以相反的顺序尝试时
>>allentries = MyEntry.objects.all()
>> annot = allentries.annotate(dailycount=Count('entrydate'))
>>annot[:2]
[ <MyEntry ..2013-2-21>,
<MyEntry ..2013-2-14> ]
>>annot[0].dailycount
1 #even tho there are many entries on that date
>>annot[1].dailycount
1 #even tho there are many entries on that date
然后应用值()
>>annotvals = annot.values('entrydate')
>>annotvals[:2]
[{'today': datetime.date(2013, 2, 21)},
{'today': datetime.date(2013, 2, 14)}]
我不确定我是否清楚地遵循了这些……有人能解释一下为什么反过来不能作为第一个吗?