Question

I have two models

class A(models.Model):
    title = models.CharField()

class B(models.Model):
    heading = models.ForeignKey(A)
    content = models.CharField()

When I tried to do the below I'm getting IntegrityError: b.heading may not be null

b = B()
a = A()

b.heading = a
b.heading.title = 'title'
b.content = 'content'

b.heading.save()
b.save()

Why is this happening? can't we work with objects this way?

Was it helpful?

Solution

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top