我正在使用 django 1.5,我正在尝试做这样的事情:
quotes = formset.save()
user = client_form.save()
for quote in quotes:
quote.client = user
quotes.save()
但是列表没有 save() 方法,所以是否有一些内置功能可以做类似的事情?
我在关于 Django 中的批量保存对象的SO Question 上找到了这个答案
django 1.5 仍然是真的吗?有没有办法避免对列表的每个对象进行 save() 调用?
这是我的实际视图代码:
def new_quote(request):
QuoteLineFormSet = modelformset_factory(QuoteLine, form=QuoteLineForm, extra=2)
if request.method == 'POST':
formset = QuoteLineFormSet(request.POST, request.FILES, queryset=QuoteLine.objects.none())
quote_form = QuoteForm(request.POST, request.FILES)
if formset.is_valid() and quote_form.is_valid():
quote_lines = formset.save(commit=False)
#quote_lines = formset.get_queryset()
quote = quote_form.save()
for quote_line in quote_lines:
quote_line.quote = quote
quote_line.save()
request.session['quote_id'] = quote.id
return HttpResponseRedirect(reverse('new_client'))
else:
formset = QuoteLineFormSet(queryset=QuoteLine.objects.none())
quote_form = QuoteForm()
return render(request, 'request_quote_form.html', {
'formset': formset,
'quote_form': quote_form,
})
我现在的解决方案
quote_line_ids = [item.pk for item in formset.save()]
quote_lines_qs = QuoteLine.objects.filter(pk__in=quote_line_ids)
quote = quote_form.save()
quote_lines_qs.update(quote=quote)