2013-10-28 139 views
0

我有模型是這樣的:如何在Django中保存ManyToMany字段?

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

因爲你'new_guest.status = status'您保存了'new_guest後' –

+0

如果我在'new_guest.user = request.user'後面寫'new_guest.status = status',稍後再'new_guest.save()'我得到這個錯誤:'「需要有一個值在這個多對多關係可以使用前,可以使用字段「guest」 – pynovice

+0

如果表單具有'status'字段,則不需要將其顯式設置爲'new_guest.status =狀態',而不是'form.save_m2m()'。 – Rohan

回答

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) 

希望你瞭解我和我的英語:)

+0

''客人'的對象沒有屬性'status_set''錯誤,同時保存! – pynovice

+0

什麼django版本我們使用?https://docs.djangoproject.com/en/1.5/ref/models/relations/ – McAbra

相關問題