Django onetoonefield does not save instance

I am working on an application in which I have two models for this question, let’s name them A and B. I want to have another model where I will 'bind' both A and B to make it easier for me to find an instance of B which refers to A. So, I came up with:

class ABLink(models.Model):
    a = models.OneToOneField(A, null=True)
    b = models.OneToOneField(B, null=True)

I use the Django post_save signal for model A to make a link:

mashup, cr = ABLink.objects.get_or_create(a=instance)
if cr:
     mashup.b = B()
else:
    if mashup.b is None:
        mashup.b = B()
.... (assign values to mashup.b attributes)
mashup.b.save()
mashup.save()

The problem is that mashup.b is never stored in the database. When checking, phpMyAdmin b is set to NULL. Any idea what I can do wrong

+3
source share
1 answer

First create an instance B, assign attributes to it, call save on it (now it has id), and then assign it mashup.b:

if cr:
     b = B()
else:
    if mashup.b is None:
        b = B()

#.... (assign values to b attributes)

b.save()
mashup.b = b
mashup.save()
+4
source

All Articles