Hi everyone
I have three models:
class Parent(models.Model):
name = models.CharField(blank=True, max_length=20)
... # other fields
class OneChild(models.Model):
name = models.CharField(blank=True, max_length=20)
parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, blank=True, null=True, related_name='one_childs')`
... # other fields
class TwoChild(models.Model):
name = models.CharField(blank=True, max_length=20)
parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, blank=True, null=True, related_name='two_childs')`
... # other fields
Is there any options to perform some action while saving parent model instance with changed foreignkey values for childs? For example, write to file new names of childs?
Now i try to use post_save signal for Parent, but i got current names instead of new.
Welcome @SousageMouse !
You don’t need to use signals, or anything like that.
You could extend the Parent.save()
method and have it call an update method (when necessary) on the child models. (Then, you only need to ensure that all updates to Parent
use that save method.)
If you need to ensure that this will always be done under all circumstances, then you would need to write a trigger on the database to force the update to occur at the database layer.
Many thanks for your reply.
Will it work if the child models is changed, not parent?
Maybe i dont get your answer
I was addressing your question:
If there are more situations, such as saving one of the Child
objects and not the Parent
, then yes, there are other things that would need to be done. If you want to change the Parent
when a Child
changes, then that would be something added to the Child.save()
method.
In that case, we would need a more detailed explanation of your set of requirements here.
What is everything that you are looking to do here?
A child holds only the parent’s primary key value.
Therefore, unless the parent’s pk is changed or deleted, changing the contents of each model will not affect it.
The main task is to create a json with the values of the primary model, including values from the linked models, when saving the main model or the linked models. The problem is that when a link is updated, the json does not contain the new link, but the old one (or none if there was none). For the sake of experiment I changed the link to m2m and using m2m_changed got the current links. The question is whether this can be achieved on fk and how
I’m sorry but this description is still too vague. I don’t follow what the sequence of events is supposed to be, what the data is being used, and what your ultimate objective is.
For me to try and help you here, you are going to need to provide a detailed and specific example of exactly what it is you’re trying to do. Please post the actual code involved and sample data showing the issue.