I am using django 1.5 and i am trying to do something like this :
quotes = formset.save()
user = client_form.save()
for quote in quotes:
quote.client = user
quotes.save()
But lists dont have a save() method so is there some built in functionality to do something similar ?
I found this nswer on SO Question about batch save objects in Django
Is it still True with django 1.5 ? Is there no way to avoid the save() call on each object of the list ?
here is my actual view code:
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,
})
My solution for now
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)
You can use update()
method on a queryset.
Also see this question and answer: Django: form that updates X amount of models