MultipleChoiceField 创建多个对象

MultipleChoiceField create multiple objects

我在表单中使用 MultipleChoiceField。我想将所有 selected 值添加到数据库,但我使用的下一个代码仅添加用户 select 的最后一个值。我在我的视图中尝试创建多个数字对象。我哪里做错了?

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)

您应该添加 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()