Django ManyToManyField,模型匹配自定义通过表

c9qzyr3d  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(101)

我有一个类似于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)的唯一解决方案?

ukqbszuj

ukqbszuj1#

您需要的是FK related_name:

class Membership(models.Model):
    group = models.ForeignKey(
        Group, 
        on_delete=models.CASCADE, 
        related_name="members"
    )
    ...
>>> g1 = Group.objects.get(pk=1)
>>> g1.members.all()

相关问题