0

I'm trying to set a non nullable OneToOneField object (which hasn't been set) in the pre_save method.

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 stored in the database, I get this error as if the A object doesn't point to B

django.db.utils.IntegrityError: NOT NULL constraint failed: app_a.b_id

If I set null=True in the field definition, of course I don't get the NOT NULL constraint failed error. But still, the A object doesn't store the reference to the B object.

I'm guessing this is because in the original A object there is no B reference, so when save is executed somehow it doesn't think it should save the b property.

Any ideas how to do this?

Martin Massera
  • 1,718
  • 1
  • 21
  • 47

1 Answers1

0

So, I found the source of the problem!

This error happens when you assign the object before saving it. If you save the object and assign it later, it saves the object correctly:

b = B()
b.save()
instance.b = b
Martin Massera
  • 1,718
  • 1
  • 21
  • 47