3

这是我的models.py

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重新定义的保存函数中保存计算的数据...这显然不起作用,因为Invoices先保存...

视图.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的新手...

谢谢!

4

1 回答 1

0

我不知道这是否是正确的方法......但它的工作原理......

我所要做的就是created_invoice再次拯救……所以

created_invoice.save()
form.save()
created_invoice.save()
于 2011-06-08T06:38:45.333 回答