This actually has to do with the order you do things.
When first assigning a
to b.heading
, the A
object is not yet saved and doesn't have a primary key. Thus, on assignment, b.heading_id
will remain None
. b.heading
doesn't know anything about b
, so when saved, b.heading_id
will remain None
. When saving b
, it expects b.heading_id
to have a valid non-null value, which it obviously hasn't. Therefore, an IntegrityError
is raised.
What you should do, is do the assignment after saving a
:
b = B()
a = A()
a.title = 'title'
a.save()
b.heading = a
b.content = 'content'
b.save()