theatlantic / django-nested-admin

Django admin classes that allow for nested inlines
http://django-nested-admin.readthedocs.org/
Other
690 stars 97 forks source link

How to override Model.save() of a nested model #204

Open keehun opened 2 years ago

keehun commented 2 years ago

I have the following models (made up for illustration purposes):

class Parent(models.Model):
    name = models.CharField()

class Child(models.Model):
    parent = models.ForeignKey(Parent, related_name='children', on_delete=models.PROTECT)`
    name = models.CharField()
    toys_summary = models.CharField(editable=False)

class Toys(models.Model):
    name = models.CharField()
    child = models.ForeignKey(Child, related_name='toys', on_delete=models.PROTECT)`

I only register admin for Parent. I want admin for Toy nested for each Child and then each Child nested in Parent.

My problem is I don't understand how to calculate the Child.toys_summary when the Parent admin gets saved WHEN toys have been added/deleted which takes into account the newly changed Toy instances.

I currently override Parent.save() to generate content for Child.toys_summary where I do something like:

def save(self, *args, **kwargs):
    for child in self.children.all():
        child.toys_summary = self.generate_toy_summary(child)
    super().save(*args, **kwargs)

As you can imagine, generate_toy_summary will iterate over its toys.all() and generate that content.

The problem with this method is, it works for toys that are already present on the admin form. It does NOT have the changed Toy instances (added/deleted).

Should I be overriding some other method? I am new to Django, so there is a lot I could be misunderstanding. Thank you.