gpt4 book ai didi

python - MultipleChoiceField 创建多个对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:57:18 25 4
gpt4 key购买 nike

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

模型.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)

表单.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()

关于python - MultipleChoiceField 创建多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43590524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com