当调用save_related时,我需要访问内联表单集中所有表单的两个字段,以及 save_related只允许我访问已更改的表单/数据。
我的问题的任何其他解决方案都是,所以这里是:
class Invoice(models.Model):
invoice = models.CharField(max_length=10, blank=True, null=True, unique=True)
total = models.PositiveIntegerField(blank=True, null=True)
class InvoiceItem(models.Model):
invoice = models.ForeignKey(Invoice, related_name='items')
service = models.ForeignKey(Service)
quantity = models.PositiveIntegerField(blank=False, default=1)
price = models.PositiveIntegerField(blank=False, default=0)
class InvoiceItemInline(admin.TabularInline):
model = InvoiceItem
class InvoiceAdmin(admin.ModelAdmin):
inlines = [InvoiceItemInline]
def save_related(self, request, form, formsets, change):
invoice = form.instance
invoice.total = 0
for inlines in formsets:
for inline_form in inlines:
invoice.total = invoice.total + inline_form.cleaned_data['price'] * inline_form.cleaned_data['quantity']
invoice.save()
super(InvoiceAdmin, self).save_related(request, form, formsets, change)
我需要计算每个发票项目的发票总额,其中每个项目的数量都是*价格。
答案 0 :(得分:5)
我无法找到解决方案,因此我保存了相关数据并使用查询集来获取已保存的数据,以便我可以进行计算并再次保存。 我想有人会称这是一个解决方法' :)
def save_related(self, request, form, formsets, change):
super(InvoiceAdmin, self).save_related(request, form, formsets, change)
invoice = form.instance
invoice.total = 0
for item in Invoice.objects.get(pk=invoice.id).items.all():
invoice.total = invoice.total + item.quantity * item.price
invoice.save()
答案 1 :(得分:1)
解决方案的解决方法。这个对我有用。刚刚将System.out.println(newList)
更改为inline_form.cleaned_data['price']
。 :)
inline_form.cleaned_data.get('price')