Django inlineformset-自定义保存方法
|
这是我的模型
class Invoices(models.Model):
...
sum_w_vat = models.DecimalField(max_digits=7, decimal_places=2, default=0)
sum_wo_vat = models.DecimalField(max_digits=7, decimal_places=2, default=0)
sum_discount = models.DecimalField(max_digits=7, decimal_places=2, default=0)
sum_vat = models.DecimalField(max_digits=7, decimal_places=2, default=0)
sum_paid = models.DecimalField(max_digits=7, decimal_places=2, default=0)
...
class InvoiceItems(models.Model):
invoice = models.ForeignKey(Invoices)
quantity = models.DecimalField(max_digits=9, decimal_places=2)
unit = models.ForeignKey(StocklistUnits, verbose_name=\'Merska enota\')
price = models.DecimalField(max_digits=9, decimal_places=2)
vat = models.DecimalField(max_digits=4, decimal_places=3)
discount = models.DecimalField(max_digits=3, decimal_places=1)
def save(self, **kwargs):
self.invoice.sum_w_vat += (self.price * self.quantity * self.vat) * self.discount
self.invoice.sum_wo_vat += (self.price * self.quantity) * self.discount
self.invoice.sum_discount += (self.price * self.quantity) * ( self.discount / 100 )
self.invoice.sum_vat += ((self.price * self.quantity * self.vat) * self.discount) - ((self.price * self.quantity) * self.discount)
super(InvoicesItems, self).save(**kwargs)
我不知道如何将计算的数据保存到InvoiceItems
重新定义的保存函数中...这显然不起作用,因为先保存ѭ2saved ...
views.py
def edit(request, id = None):
InvoiceFormSet = inlineformset_factory(Invoices, InvoicesItems)
if id == None:
initial_data = \'\'
data = Invoices()
else:
data = get_object_or_404(Invoices, pk=id)
initial_data = \'\'
if request.method == \'POST\':
created_invoice = InvoicesForm(request.POST, instance=data)
form = InvoiceFormSet(request.POST, instance=data)
if not form.is_valid() and not created_invoice.is_valid():
//json err msg
else:
created_invoice.save()
form.save()
json = simplejson.dumps(response, ensure_ascii=False)
return HttpResponse(json, mimetype=\"application/json\")
else:
form = InvoicesForm(instance=data, initial=initial_data)
form_items = InvoiceFormSet(instance=data)
c = {\'form\':form, \'form_items\':form_items}
c.update(csrf(request))
return render_to_response(\'crud_invoice_edit.html\', c)
我如何遍历InvoiceItems
并计算字段,然后将其插入Invoices
中。我是django的新手...
谢谢!
没有找到相关结果
已邀请:
1 个回复
疼嘶桐