Search code examples
djangoforeign-keysmodels

Django: How to retrieve last record in a reverse foreign key


Models:

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

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

each year a new registration record is created.

now I want to find all of the persons whose registration has expired or who have never registered. Something like

Person.objects.filter(registration__expires__lte=date.today() )

but of course 'registration' can't be used in the query set against person.

Do I need to store the latest registration date in the person object? Or do I do the query against the registration table first? How do I find the persons with no registrations then?


Solution

  • To find the persons with no registrations, you can annotate your person query with the registration count then filter on the annotated field:

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

    See the Django docs on annotate:

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