Django:如何在反向外键中检索最后一条记录

时间:2013-09-09 02:13:37

标签: django foreign-keys models

型号:

class Person(models.Model):
   name = ....

class Registration(models.Model):
   person  = models.ForeignKey(person)
   expires = models.DateField()

每年都会创建一个新的注册记录。

现在我想找到所有注册已过期或从未注册过的人。像

这样的东西
Person.objects.filter(registration__expires__lte=date.today() )

但当然“注册”不能在针对人的查询集中使用。

我是否需要在person对象中存储最新的注册日期?或者我首先对注册表进行查询?如何找到没有注册的人呢?

2 个答案:

答案 0 :(得分:0)

我想你想要select_related https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related

person.objects.select_related('registration').filter(registration__expires__lte=date.today() )

答案 1 :(得分:0)

要查找没有注册的人,您可以使用注册计数注释您的人员查询,然后在注释字段上进行过滤:

from django.db.models import Count
Person.objects.annotate(reg_count=Count('registration')).filter(reg_count=0)

请参阅注释中的Django文档:

https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate