Reputation: 241
I am working on an application where i have two models for the purpose of this question let's call them A and B. I want to have another model where I 'link' both A and B just to make it easy for me to find the instance of B that relates 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 Django's post_save signal for model A to do the 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 mashup.b is never saved in the DB. On checking in phpMyAdmin b is set to NULL. Any idea what I may be doing wrong
Upvotes: 3
Views: 1726
Reputation: 22571
At first create B
instance, assign attributes to it, call save on it (now it have id) and then assign it to 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()
Upvotes: 4