Django多对多的关系,并通过

时间:2009-08-20 17:01:56

标签: python django foreign-keys many-to-many

我想存储哪个用户邀请了另一个用户到一个群组......但是django告诉我这是一个暧昧而违反规则(这是有道理的)。

  

groups.group:中介模式   Group_to_Member有多个   用户的外键,即   模棱两可,不允许。

那我该如何正确地做到这一点?也许是一般关系?可能会工作但似乎有点复杂......这就是我接近它的方式(删除了不相关的位)

from django.contrib.auth.models import User

class UserGroup(models.Model):
    members = models.ManyToManyField(User, through='Group_to_Member')

class UserGroup_to_Member(models.Model):
    group = models.ForeignKey(UserGroup)
    member = models.ForeignKey(User)

    invited_by = models.ForeignKey(User, related_name="group_invited_users")

解决方案

好的,所以我做了一些你们提供的答案的结合(谢谢!)和我在互联网上发现的东西以及我自己公认的微薄的python-fu:

from django.contrib.auth.models import User

class UserGroup(models.Model):
    # notice there is no member object here
    ... other model data

    def add_member(self, **kwargs):
        g2m = UserGroup_to_Member(group = self,  **kwargs)
        g2m.save()

    def remove_member(self, member):
        g2m = UserGroup_to_Member.objects.get(group=self, member=member)
        g2m.delete()

    # This is not elegant at all, help please? I'm pretty sure it isn't
    # as bad on the database as it looks though.
    def get_members(self):
        g2ms = UserGroup_to_Member.objects.filter(group=self)
        member_ids = [g2m.member.id for g2m in g2ms]
        members = User.objects.none()
        for id in member_ids:
            members = members | User.objects.get(id=id)
        return members

class UserGroup_to_Member(models.Model):
    group = models.ForeignKey(UserGroup)
    member = models.ForeignKey(User)

    invited_by = models.ForeignKey(User, related_name="group_invited_users")

2 个答案:

答案 0 :(得分:8)

您必须自己管理:

class MyGroup(models.Model):
    name = models.CharField(max_length=100)

class Membership(models.Model):
    group = models.ForeignKey(MyGroup)
    member = models.ForeignKey(User)

    invited_by = models.ForeignKey(User, related_name='invited_set')

然后代替group.members.all() group.membership_set.all()

另外,我不会使用'Group'作为您的模型名称,因为Django已经有了一个Group对象。

答案 1 :(得分:0)

如果您使用的是Django 1.7,则可以。

来自文档:https://docs.djangoproject.com/en/1.7/topics/db/models/#extra-fields-on-many-to-many-relationships

  

在Django 1.6及更早版本中,包含多个的中间模型   任何参与多对多模型的外键   以前的关系是被禁止的。