我在表单中使用了MultipleChoiceField我想将所有选定的值添加到数据库中,但我使用的下一个代码只添加用户选择的最后一个值。我试图在我的视图中创建多个数字对象。我错在哪里了?
型号.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'),
)

视图.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()

07-26 07:14