【问题标题】:Django: How to retrieve last record in a reverse foreign keyDjango:如何检索反向外键中的最后一条记录
【发布时间】:2013-09-09 02:13:36
【问题描述】:

型号:

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 对象中存储最新的注册日期吗?还是我先查询注册表?那么如何找到没有注册的人呢?

【问题讨论】:

    标签: django foreign-keys models


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 对于有两个注册的用户,一个已经过期,一个还没有,这并不能解决我的问题。我需要找到所有没有注册(下面的答案在那里有效)或只有注册已过期的用户。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      相关资源
      最近更新 更多