0

这些模型定义如下:

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's的最新'Bar's,即

[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)

这可能会花费很多时间,是否可以通过使用查询集过滤器来实现?

4

1 回答 1

0

如果这是一个对象列表,那么这应该有效:

MyModel.objects.values('name').annotate(max_created_date=Max('created_date'))
于 2013-08-22T11:58:59.410 回答