这些模型定义如下:
from django.db import models
class Foo(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return u'%s' % self.name
def latest_bar(self):
try:
return self.bar_set.latest()
except Bar.DoesNotExist:
return None
class Bar(models.Model):
name = models.CharField(max_length=100)
foo = models.ForeignKey(Foo)
created_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u'%s' % self.name
class Meta:
ordering = ('-created_date',)
get_latest_by = 'created_date'
然后将记录创建为:
f1 = Foo.objects.create(name="F1")
f1.save()
f2 = Foo.objects.create(name="F2")
f2.save()
f3 = Foo.objects.create(name="F3")
f3.save()
b1 = Bar.objects.create(name='B1', foo=f1)
b1.save()
b2 = Bar.objects.create(name='B2', foo=f1)
b2.save()
b3 = Bar.objects.create(name='B3', foo=f1)
b3.save()
b4 = Bar.objects.create(name='B4', foo=f2)
b4.save()
b5 = Bar.objects.create(name='B5', foo=f2)
b5.save()
b6 = Bar.objects.create(name='B6', foo=f3)
b6.save()
b7 = Bar.objects.create(name='B7', foo=f3)
b7.save()
我想得到的是最新的'所有'Foo的吧',这是
[f1.latest_bar(), f2.latest_bar(), f3.latest_bar()]
=> [<Bar: B3>, <Bar: B5>, <Bar: B7>]
因为可能有大量的Foo,如果我这样做:
bars = []
for f in Foo.objects.all():
b = f.latest_bar()
if b:
bars.append(b)
这可能会耗费大量时间,是否可以通过使用queryset过滤器来实现?
答案 0 :(得分:0)
如果这是一个对象列表,那么这应该有效:
MyModel.objects.values('name').annotate(max_created_date=Max('created_date'))