我有一个类似于Django文档中的Membership
示例的情况(https://docs.djangoproject.com/en/4.2/topics/db/models/#extra-fields-on-many-to-many-relationships)。
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
persons = models.ManyToManyField(Person, through="Membership")
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
虽然这可以通过g1.persons
获得Group
的所有Person
s,但我希望获得所有Membership
s。
从概念上讲,类似于以下内容:
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Membership, through="Membership")
但这不起作用,因为显然Membership
本身没有外键。
有没有一种方法可以设置我想要的(即)通过g1.members
方便会员访问)?或者是手动通过Membership.objects.filter(group=g1.pk)
的唯一解决方案?
1条答案
按热度按时间ukqbszuj1#
您需要的是FK related_name: