0

我有两个模型:

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)
4

1 回答 1

1

Pankaj Singh 在 Django 邮件列表中回答了这个问题

这是解决方案:我测试了以下代码并且它有效。

模型.py
from 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)
于 2013-02-05T07:11:07.727 回答