Home > database >  Reverse look-up with related name
Reverse look-up with related name

Time:10-19

Suppose these models:

class Person (models.Model):
    pass

and

class Marriage (models.Model):
    person = models.ForeignKey(Person, on_delete = models.CASCADE, related_name='person')
    person_2 = models.ForeignKey(Person, on_delete = models.CASCADE, related_name='person_2')

How can I filter persons through the ID of a Marriage field (e.g. the ID)? That is, my goal is to do something like Person.objects.filter(marriage__id=32). I understand that the related name has some role there, but for example Person.objects.filter(person_2__marriage__id=32) doesn't seem to work either.

Thank you!

CodePudding user response:

It'd say you can remove the related_name and use the following construct:

mariage = Mariage.objects.get(id=32)
person = mariage.person
person2 = mariage.person_2

However, it depends on what you're trying to achieve. With something like:

class Marriage (models.Model):
    person = models.ForeignKey(Person, on_delete = models.CASCADE, related_name='mariage_person_1')
    person_2 = models.ForeignKey(Person, on_delete = models.CASCADE, related_name='mariage_person_2')

You should be able to run queries such as:

from django.db.models import Q
query = Q(mariage_person_1=32) | Q(mariage_person_2=32)
persons = Person.objects.filter(query)
  • Related