Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
keehun opened this issue Nov 12, 2021 · 0 comments
Open

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

keehun opened this issue Nov 12, 2021 · 0 comments

Comments

@keehun
Copy link

keehun commented Nov 12, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant