Override the save() of the child? On Sun, 10 Feb, 2019, 7:04 PM Nick Emery <nickemer...@gmail.com wrote:
> I am trying to wrap up my first app using Django (specifically Django > Rest Framework which may change the save behavior), but have run into an > issue that I haven't been able to solve for about 10 hours now. > > I am trying to override the save() method of a model to modify a field on > a bunch of child objects when it is created; however, I can't figure out > *any* way get the objects or ids for the children. > > My code looks something like: > class Parent(models.Model): > """When I create this, I want the children to be modified.""" > def save(self, *args, **kwargs): > if not self.pk: > self._begin(*args, **kwargs) > else: > super(Parent, self).save(*args, **kwargs) > > def _begin(self, *args, **kwargs): > super(Parent, self).save(*args, **kwargs) > print(self.child_set.all()) # --> This gives: "<QuerySet []>" > for i in self.child_set.all(): > i.last_name = self.last_name > i.save() > > last_name = models.CharField(max_length=100) > > > class Child: > parent = models.ForeignKey( > 'Parent', > on_delete=models.SET_NULL, > null=True, > ) > last_name = models.CharField(max_length=100) > > ANY way to modify the children when the parent is saved would be a life > saver (even if hacky or sub-optimal). > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/24c7156b-6873-4cd3-952e-dc819fa72be0%40googlegroups.com > <https://groups.google.com/d/msgid/django-users/24c7156b-6873-4cd3-952e-dc819fa72be0%40googlegroups.com?utm_medium=email&utm_source=footer> > . > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAD-d1sb3WVXk262-dfKuJUZ_9Kj49NDzShyv5ivL_SRrAiaMmQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.