How to initialize an empty object with ForeignKey in Django?

Viewed 3276

My models.py looks like that :

class B(models.Model):
    ...

class C(models.Model):
    ...

class D(models.Model):
    ...

class A(models.Model):
    b = models.ForeignKey(B, blank=True, null=True)
    c = models.ForeignKey(C, blank=True,null=True)
    d = models.ForeignKey(D, blank=True,null=True)

In views.py, I have to initialize an empty A, and fill it later. I can use

i = A().save()

But when I try something like :

i.b.add(objectb)

This exception occurs :

'NoneType' object has no attribute 'b'

I tried to cancel the null=True :

class A(models.Model):
    b = models.ForeignKey(B, blank=True)
    c = models.ForeignKey(C, blank=True)
    d = models.ForeignKey(D, blank=True)

But then another exception occured :

A.b_id may not be NULL

I can't figure out how to initialize an empty but not "None" A.

I need your help,

Thanks you

2 Answers
Related