[Answer]-Update parent values in Django admin

1👍

This question was answered on the Django mailing list by Pankaj Singh

Here is the solution:
I tested following code and it works.

models.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)

Leave a comment