David Dahan
David Dahan

Reputation: 11172

Can't understand why foreign keys stay empty with this code

I have some code in Django 1.6:

Here are my models.py:

class MyClass1
  ... # some stuff

class MyClass2
  ... # some stuff
  fk_to_class1 = models.ForeignKey(MyClass1, blank=True, null=True)

And somewhere in a view:

list_of_objects2 = []
# list_of_objects1 contains several objects from MyClass1

for elt in list_of_objects1:
  list_of_objects2.append(MyClass2(fk_to_class1=elt))

MyClass2.objects.bulk_create(list_of_objects2)

After this, objects from MyClass2 should have the "fk_to_class1" filled with some value, but they're empty. No errors raised. I don't understand. Thanks for help.

Upvotes: 2

Views: 87

Answers (1)

Chambeur
Chambeur

Reputation: 1619

It's probably due to "list_of_objects1" which still contains the "elts" without id's.

Maybe you should, kind of "reload" your list after you saved it.

EDIT : For example, your list looks like that :

list_of_objects1 [
    elt1 {id : null}
    elt2 {id : null}
]

If you save "list_of_objects1". Your ORM will set the ids in your DB but not in your instance. So maybe you need to reload your instance from your db with the ids set.

Upvotes: 1

Related Questions