I have three models
class
Parent`(models.Model):
name = models.CharField(blank=True, max_length=20)
... # other fields
def _get_childs(self):
first_childs = [f'{child.name}' for child in self.one_childs.all()]
second_childs = [f'{child.name}' for child in self.two_childs.all()]
return [first_childs + second_childs]
@classmethod
def get_config(cls) -> str:
try:
instance = cls.objects.get()
except cls.DoesNotExist:
return ''
config = {}
for child in instance._get_childs():
config[child] = {
'interval': 1000,
... # other fields
}
return json.dumps(config, indent=4)
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`
I need to write get_config result to file (‘/tmp/config’ as example) on Parent save. everything works fine, but i get previous relations childs, not new. i tried to use it in post_save signal for Parent model, but it is does not help.
there is a signal for example
@receiver(post_save, sender=Parent)
def update_config(sender, instance, **kwargs):
config_json = instance.get_config()
file_path = ‘/tmp/config.json’
with open(file_path, 'w') as file:
file.write(config_json)
when I save Parent all values become valid except child.name’s
is there any option to achieve this?
SousageMouse is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.