如何在Django中保存ManyToMany字段?

时间:2013-10-28 07:06:47

标签: django django-orm

我有这样的模特:

class GuestStatus(models.Model):
    guest_status = models.CharField(max_length=200)
    arrangement = models.IntegerField(unique=True, help_text="Start from 1. Guest status will be arranged alphabetically.")


class Guest(models.Model):
    user = models.ForeignKey(User)
    full_name = models.CharField(max_length=250)
    status = models.ManyToManyField(GuestStatus, blank=True, null=True)
    invitation_date = models.DateTimeField(blank=True, null=True)

我希望ManyToManyField显示为复选框。这就是我这样做的原因:

class GuestForm(ModelForm):
    status = forms.ModelMultipleChoiceField(queryset=GuestStatus.objects.all().order_by('arrangement'), widget=forms.CheckboxSelectMultiple, required=False)
    class Meta:
        model = Guest
        exclude = ['user', 'invitation_date']

我想保存这样的表格:

    form = GuestForm(request.POST)
    if form.is_valid():
        status = form.cleaned_data['status']
        guest.status = status
        if status:
            invitation_date = datetime.now() 
        else:
            invitation_date = None
        new_guest = form.save(commit=False)

        new_guest.user = request.user
        new_guest.save()
        new_guest.status = status
        form.save_m2m()

        return HttpResponseRedirect('/list_guests/')

表单正在保存所有数据,但不保存status值。怎么了?此外,成功保存后如何访问模板中的状态值?感谢

1 个答案:

答案 0 :(得分:0)

我会这样做:

form = GuestForm(request.POST)
if form.is_valid():
    if status:
        invitation_date = datetime.now() 
    else:
        invitation_date = None

    new_guest = form.save(commit=False)
    new_guest.user = request.user
    new_guest.save()

    status = form.cleaned_data['status']
    for stat in status:
        new_guest.status_set.create(guest_status = stat['guest_status'], arrangement = stat['arrangement'])

    return HttpResponseRedirect('/list_guests/')

获得new_guest个实例后,您创建GuestStatus个实例并将其绑定到new_guest

如果GuestStatus是您的字典,您可以:

    for stat in status:
        gs = GuestStatus.objects.get(pk = stat['guest_status'])
        new_guest.status_set.add(gs)

希望你能理解我和我的英语:)