2017-04-24 98 views
1

我在我的表單中使用MultipleChoiceField。我想將所有選定的值添加到數據庫,但下一個我使用的代碼只添加用戶選擇的最後一個值。我在我的視圖中嘗試創建多個數字對象。我哪裏錯了?MultipleChoiceField創建多個對象

models.py:

class Requirement(models.Model): 
    code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False) 
    symbol = models.CharField(_('Symbol'), max_length=250) 
    name = models.CharField(_('Name'), max_length=250) 

forms.py:

class AddForm(forms.ModelForm): 
    symbol= forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=REQUIREMENTS_CHOICES,) 

    class Meta: 
     model = Requirement 
     fields = ('symbol',) 


REQUIREMENTS_CHOICES = (
    ('A', 'Name A'), 
    ('B', 'Name B'), 
    ('C', 'Name C'), 
) 

views.py:

def requirement_add(request): 
    data = dict() 
    if request.method == 'POST': 
     form = AddForm(request.POST) 
     if form.is_valid(): 
      list = dict(REQUIREMENTS_CHOICES) # {'C': 'Name C', 'A': 'Name A', 'B': 'Name B'} 
      symbols = form.cleaned_data.get('symbol') # ['A', 'B', 'C'] 
      requirement = form.save(commit=False) 
      for symbol in symbols: 
       requirement.symbol = symbol 
       requirement.name = list[symbol] 
       requirement.save() 
      data['form_is_valid'] = True 
      requirements = Requirement.objects.filter() 
      context = {requirement': requirement, 'requirements': requirements} 
      data['html_requirement'] = render_to_string('project/requirement_list.html', context) 
     else: 
      data['form_is_valid'] = False 
    else: 
     form = AddForm() 
    context = {'form': form} 
    data['html_requirement_form'] = render_to_string('project/requirement_add.html', context, request=request) 
    return JsonResponse(data) 

回答

1

您應該添加requirement.pk = None使以save每次調用將在數據庫中插入新行:

for symbol in symbols: 
    requirement.symbol = symbol 
    requirement.name = group_requirement_list[symbol] 
    requirement.pk = None 
    requirement.save() 

看到這裏https://docs.djangoproject.com/en/dev/ref/models/instances/#how-django-knows-to-update-vs-insert的文檔。

編輯:

說明:在這個循環requirement.save()的第一次迭代將在數據庫中插入新行如你所願。但在此之後requirement將具有新行的主鍵,並且Django將嘗試更新它,而不是創建一個新的行。

替代解決方案:你能避免這一切,如果你把requirement = form.save(commit=False)在for循環是這樣的:

symbols = form.cleaned_data.get('symbol') # ['A', 'B', 'C'] 
for symbol in symbols: 
    requirement = form.save(commit=False) 
    requirement.symbol = symbol 
    requirement.name = group_requirement_list[symbol] 
    requirement.save() 
+0

謝謝! 'requirement.pk = None'適用於我,但我不明白它爲什麼可行xD你能解釋一下嗎?正如你可以看到代碼字段是我的PK,我也使用默認= uuid.uuid4。所以我認爲它會自動創建pk。也感謝您的鏈接。 –

+0

不客氣!我添加了一個解釋和一個替代解決方案。 –