I have two models, A and B that are one-to-one related. How do I use Django’s bulk_create() to successfully create them together as a bulk? I’m using Django’s auto-generated IDs for both models. Thank you so much.
You don’t. At least not as one call.
The bulk-create method is a method on a model class. You pass it something that can be converted to a
list containing the set of the model being inserted.
What I believe you ought to be able to do is insert your base table entries first, then assign the appropriate key to the data being added to the tables relating to the base table, and do the bulk_create on it. (Note: The set of objects being inserted through bulk_create can have the pk assigned when being inserted, even if it an “auto-generated id”.)
I tried executing two
bulk_create()s and I tried to link them together with a
bulk_update() but I get the error
ValueError: All bulk_update() objects must have a primary key set.. How do I solve this please? Thank you.
What database engine are you using?
Postgres / Postgis (post must be at least 20 characters… so here it is …)
Do your first bulk_create.
Then, assign the related field of the objects being used to populate the second table to their corresponding entries of the first table.
Then do your second bulk create.
Thank you Ken. Now I’m getting this error:
ValueError: bulk_create() prohibited to prevent data loss due to unsaved related object 'person'.
people_records = [ Person(name=‘A’, age=1), Person(name=‘B’, age=2)] # people_records # [<Person: A>, <Person: B>] people = Person.objects.bulk_create(people_records) # people # <QuerySet [<Person: A>, <Person: B>]> hobby_records = [ Hobby(name=‘H1’, person = people), Hobby(name=‘H2’, person=people) ] # hobby_records # [<Hobby: H1>, <Hobby: H2>] hobbies = Hobby.objects.bulk_create(hobby_records) # ValueError: bulk_create() prohibited to prevent data loss due to unsaved related object 'person'.
I can’t recreate these symptoms based on the code snippet here. I’ve done this in the Django shell and it works exactly as expected.
In : def mp(): ...: pr=[MPerson(name="C", age=3), MPerson(name="D", age=3)] ...: pe=MPerson.objects.bulk_create(pr) ...: hr=[MHobby(name='H1', person=pe), MHobby(name='H2', person=pe)] ...: ho=MHobby.objects.bulk_create(hr) ...:
(Pardon the class names - I mangle them to keep examples separate in my test environment.)
It’s possible that there’s some different in the model definition that would explain the different results. Can you post the models you’re using for this?
i have encountered the exact same problems.
Are you certain you don’t have a many-to-many relationship on your Person and Hobby models?