使用ModelMultipleChoiceField和中间模型保存多对多字段

时间:2015-07-10 02:16:38

标签: python django python-2.7 django-1.7

我有以下型号。

class User(models.Model):
    ...

class Group(models.Model):
    name = models.CharField(max_length=255)
    creater = models.ForeignKey(User)
    users = models.ManyToManyField(User, through='GroupUser', through_fields=('group', 'user'))

class GroupUser(models.Model):
    group = models.ForeignKey(Group)
    user = models.ForeignKey(User)
    date_joined = models.DateField(auto_now_add=True, editable=False)

对于admin.py,我定义了这些。

class GroupAdminForm(forms.ModelForm):
    users = forms.ModelMultipleChoiceField(
        queryset=User.objects.all(), 
        required=False,
        widget=FilteredSelectMultiple(
            is_stacked=False,
        ),
    )

    class Meta:
        model = Group

    def __init__(self, *args, **kwargs):
        super(GroupAdminForm, self).__init__(*args, **kwargs)
        if self.instance.id:
            self.fields['users'].initial = self.instance.users.all()

    # Version 1 save()
    def save(self, commit=True):
        group = super(GroupAdminForm, self).save(commit=False)
        if group.id:
            group.users = self.cleaned_data['users']
            if commit:
                group.save()
                group.save_m2m()
        return group

    # Version 2 save()
    def save(self, commit=True):
    group = super(GroupAdminForm, self).save(commit=False)
    if group.id:
        for user in self.cleaned_data['users']:
            u = GroupUser(group=group, user=user)
            u.save()
        if commit:
            group.save()
    return group

class GroupAdmin(models.ModelAdmin):
    ...
    form = GroupAdminForm
    filter_horizontal = ['users']
    ...

问题是无论我使用版本1和2 save()函数,都会返回错误:

Cannot set values on a ManyToManyField which specifies an intermediary model.

我在网上发现了一些类似的问题,但我仍然无法理解如何覆盖save()函数。有什么建议吗?

我知道如果我没有定义中间模型可能会有效,但是可以这样做但仍然可以为每条记录获取date_join字段吗?

0 个答案:

没有答案