我有两个模型:
class Tickets(models.Model):
ticketnumber = models.IntegerField()
total_amount = models.DecimalField()
class TicketItems(models.Model):
name = models.Charfield(max_length=30)
ticket = models.ForeignKey(Tickets)
price = models.DecimalField()
amount = models.IntergerField()
我有一个内联管理页面,用户可以添加 TicketItems。如何在保存时更新所有 TicketItems 的模型票的总金额(价格 * 金额)?
Django 文档告诉我在 admin.py 中添加这个:
class TicketAdmin(admin.ModelAdmin):
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
instance.user = request.user
instance.save()
formset.save_m2m()
我尝试了很多东西,但我无法更新总金额。这是我的 admin.py:
class TicketitemsInline(admin.TabularInline):
model = Ticketitems
class TicketsAdmin(admin.ModelAdmin):
inlines = [
TicketitemsInline,
]
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
instance.user = request.user
instance.save()
instance.update_total_amount()
formset.save_m2m()
admin.site.register(Tickets, TicketsAdmin)