反向查找相关名称

Reverse look-up with related name

假设这些模型:

class Person (models.Model):
    pass

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

如何通过 Marriage 字段的 ID(例如 ID)过滤人员?也就是说,我的目标是做类似 Person.objects.filter(marriage__id=32) 的事情。我知道相关名称在那里有一些作用,但是例如 Person.objects.filter(person_2__marriage__id=32) 似乎也不起作用。

谢谢!

它会说您可以删除 related_name 并使用以下结构:

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

但是,这取决于您要实现的目标。像这样:

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

您应该能够 运行 查询,例如:

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