Django将某些字段保存到数据库,但不保存其他字段

问题描述 投票:0回答:1

我正在尝试通过表单保存一些数据,并且正在尝试使用FormSet。要保存的数据是包含Product的发票它是Details

我能够在一个地方渲染所有内容(这并不简单),将发票和详细信息保存到数据库。由于某种原因,Detail表正在保存产品ID,而不是发票ID。这是我的models.py

class Detail(models.Model):
    invoice = models.ForeignKey(Invoice, null=True, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=1)
    subtotal = models.DecimalField(max_digits=9 , null=True, decimal_places=2)

class Invoice(models.Model):
    date = models.DateField(default=datetime.date.today)
    number = models.CharField(max_length=10, default='0000000000')
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
    products = models.ManyToManyField(Product, null=True, blank=True)
    total = models.DecimalField(max_digits=9 , null=True, decimal_places=2)

这是我的views.py

def invoice_new(request):
    DetailFormSet = formset_factory(DetailForm, extra=2)
    if request.method == "POST":
        invoice_form = InvoiceForm(request.POST)
        detail_formset = DetailFormSet(request.POST)
        if invoice_form.is_valid() and detail_formset.is_valid():
            invoice = invoice_form.save(commit=False)
            invoice.save()
            for details in detail_formset:
                details.save()
            return redirect('invoice_detail', pk=invoice.pk)
        else:
            return redirect('invoice_error')
    else:
        invoice_form = InvoiceForm()
        detail_formset=formset_factory(DetailForm, extra=2)
        return render(request, 'invoice/invoice_edit.html', {'invoice_form': invoice_form, 'detail_form': detail_formset} )

我尝试将其添加到for循环的主体中:

details.invoice_id = invoice.pk

invoice.id打印OK,但不会将数字保存到DB。我看不到它怎么能很好地提取产品ID,而不是发票。

我正在添加forms.py

class InvoiceForm(forms.ModelForm):
    class Meta:
        model = Invoice
        fields = ['date','number','supplier']
        total = forms.DecimalField(disabled=True)

class DetailForm(forms.ModelForm):
    class Meta:
        model = Detail
        fields = ['product','quantity']
python django django-models django-views formset
1个回答
0
投票

您可以在保存表单之前设置发票ID。

    if invoice_form.is_valid() and detail_formset.is_valid():
        invoice = invoice_form.save(commit=False)
        invoice.save()
        for details in detail_formset:
            details.invoice = invoice # Set the invoice
            details.save()
© www.soinside.com 2019 - 2024. All rights reserved.