假设这些模型:
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')
如何通过婚姻字段的ID(例如ID)筛选人员?也就是说,我的目标是做一些类似Person.objects.filter(marriage__id=32)的事情。我理解相关的名称在那里有一些作用,但例如Person.objects.filter(person____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)