我有两种模式:
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)
答案 0 :(得分:1)
Pankaj Singh在Django邮件列表上回答了这个问题
以下是解决方案: 我测试了以下代码并且它可以工作。
models.pyfrom django.db import models
class Ticket(models.Model):
ticketnumber = models.IntegerField()
total_amount = models.DecimalField(max_digits=7, decimal_places=2,
blank=True)
def update_total_amount(self):
total = 0
for ti in self.ticketitem_set.all():
total += ti.price * ti.amount
self.total_amount = total
self.save()
class TicketItem(models.Model):
name = models.CharField(max_length=30)
ticket = models.ForeignKey(Ticket)
price = models.DecimalField(max_digits=7, decimal_places=2)
amount = models.IntegerField()
#### admin.py
from django.contrib import admin
from tickets.models import Ticket, TicketItem
class TicketItemInline(admin.TabularInline):
model = TicketItem
class TicketAdmin(admin.ModelAdmin):
inlines = [TicketItemInline,]
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
instance.save()
formset.save_m2m()
instance.ticket.update_total_amount()
admin.site.register(Ticket, TicketAdmin)