Ok I found the source of the problem, which is the order of assigning and saving the b object. Saving first and assigning later works:
b = B() b.save() instance.b = b On Sunday, September 22, 2019 at 10:53:32 AM UTC-3, Martín Massera wrote: > > Hi guys I'm posting this here before creating a ticket, not sure if this > is intended behavior but it looks like a bug to me. > > I have a pre_save method that populates a non-nullable OneToOneField in > case it is not set at save time. > > class A(Model): > > b = models.OneToOneField(B, on_delete=CASCADE) > > @staticmethod > def pre_save(sender, instance, **kwargs): > try: > instance.b > except RelatedObjectDoesNotExist: > instance.b = B() > instance.b.save() > > pre_save.connect(A.pre_save, A) > > Even though the B object gets created and saved, the reference is not > saved to the instance so I get a "not null constraint failed" error in the > database. > > If I set the field as nullable, of course I don't get the not null error, > but the property instance.b is still not being updated. > > How can I force the update of this property? Is this a bug or intended? > From the docs it seems this would be one of the purposes of the pre_save > signal (ie: the typical "calculate the slug of a field in the pre_save" > example) > I'm using django 2.2.4 > > Thanks! > -- 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 view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b60e124b-242c-47d2-80f3-825f52fc679a%40googlegroups.com.