如何使用多对多关系和映射表保存创建的对象?

时间:2014-08-06 21:05:52

标签: python mysql django many-to-many

使用accepted answer中的Class-based views for M2M relationship with intermediate model,如果我将其外键的ID硬编码到Membership,我可以保存Group,尽管没有任何相关信息date_joinedinvite_reason,但填写表单的Group永远不会被保存,因此我无法为Membership提供正确的ID。事实上,每当我尝试在接受的答案中的代码之前或之后保存group时,我都会获得与OP相同的AttributeError

  

无法在指定中间模型的ManyToManyField上设置值。改为使用会员经理。

有没有办法让这段代码真正起作用?我被误导了吗?通过映射表保存具有多对多字段的东西的正确方法是什么?我发现的答案让我感到困惑,而不是帮助我。

作为参考,如果问题被删除:

models.py

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
    return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

接受的答案(附加一行硬编码ID)

from django.views.generic.edit import ModelFormMixin
from django.views.generic import CreateView

class GroupCreate(CreateView):
    model = Group

    def form_valid(self, form):
        self.object = form.save(commit=False)
        for person in form.cleaned_data['members']:
            membership = Membership()
            membership.group = self.object
            membership.group_id = 108 # Added line
            membership.person = person
            membership.save()
        return super(ModelFormMixin, self).form_valid(form)

注意:我必须添加id行,因为如果没有它,我会得到以下IntegrityError

  

列'group_id'不能为空

如果它是相关的,我试图将其保存到MySQL数据库。

0 个答案:

没有答案