Answer the question
In order to leave comments, you need to log in
Creating objects in 2 django models at once?
There are 2 models
class QualityControl(models.Model):
object = models.ForeignKey(Object, verbose_name=u'Объект')
type = models.ForeignKey(QCType, verbose_name=u'Тип контроля')
company = models.ForeignKey(Company, verbose_name=u'Организация')
number = models.CharField(max_length=200, verbose_name=u'Номер')
date = models.DateField(verbose_name=u'Дата')
class QCConstruction(models.Model):
qc = models.ForeignKey(QualityControl, verbose_name=u'Документ')
work = models.ForeignKey(Work)
construction = models.ForeignKey(Construction, verbose_name=u'Конструкция')
value = models.CharField(max_length=128, verbose_name=u'Значение', blank=True)
Answer the question
In order to leave comments, you need to log in
Decided this way:
from django.forms import inlineformset_factory
class QCWorkConstructionCreateView(TemplateView):
template_name = 'executive/qc/qc-work-construction-create.html'
def get_context_data(self, **kwargs):
context = super(QCWorkConstructionCreateView, self).get_context_data(**kwargs)
works = Work.objects.filter(id__in=self.request.GET.getlist('works'))
# задаем начальные значения
initial = []
for work in works:
for con in work.constructions.all():
qc_con = dict()
qc_con['construction'] = con.id
qc_con['work'] = work.id
qc_con['value'] = ''
initial.append(qc_con)
# количество отображаемых строк formset
extra = len(initial)
# форма для документа QC
form = QCForm(self.request.user, {'object': self.request.user.profile.current_object_id})
# Formset для QCConstruction
QCformset = inlineformset_factory(QualityControl, QCConstruction, fields=('construction', 'work', 'value',), extra=extra)
context['form'] = form
context['formset'] = QCformset(initial=initial)
return context
def post(self, *args, **kwargs):
form = QCForm(self.request.user, self.request.POST)
if form.is_valid():
qc = form.save()
QCformset = inlineformset_factory(QualityControl, QCConstruction, fields=('construction', 'work', 'value',))
formset = QCformset(self.request.POST, instance=qc)
if formset.is_valid():
formset.save()
return redirect('qc_list')
Here's a variant
. You can generally do it straight on the forehead, render the form on two models, but in the models there are a lot of dependencies with other models. Be sure that you will receive all foreign key IDs upon submission. When you post a request - first save the entry for the first model.
quality_control.save()
After that, the quality_control object already has its own ID and can be pushed into the record of the second QCConstruction model
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question