Search code examples
djangodjango-modelsinitializationattributeerrornonetype

How to initialize an empty object with ForeignKey in Django?


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


Solution

  • I think you are confusing ManyToManyField and ForeignKey

    To initialize a Foreign key, you would just do:

    i = A().save()
    i.b = objectb
    i.save()
    

    where objectb is an instance of class B

    The reason i.b.add(objectb) throws an exception is,

    i.b is accessing the attribute b of the model instance i, which is None, and when the ORM tries to call the add on b, it is indeed None. Hence the error.