Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting/Querying objects from django bulk_create?

If I use bulk_create to insert objects:

objList = [a, b, c,] #none are saved
model.objects.bulk_create(objList)

The id's of the objects would not be updated (see https://docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create). So I can't use these guys as foreign key objects. I thought of querying them back from the database after they're bulk created and then using them as foreign key objects, but I don't have their ids to query them. How do I query these objects from the database (given that there can be duplicate values in columns other than the id)? Or is there a better way to make bulk created items as foreign keys?

like image 601
Derek Avatar asked Dec 04 '25 16:12

Derek


1 Answers

If you have only three objects, as in your example, you might want to call save on each individually, wrapping the calls within a transaction, if it needs to be atomic.

If there are many more, which is likely the reason for using bulk_create, you could potentially loop through them instead and call save on each. Again, you could wrap that in a transaction if required. Though, one might not like this option as running tonnes of insert queries could potentially be a problem for some database setups.

Alternatively, a hack would be to add some known unique identifier to the object so you could re-query these after save.

like image 194
deadbeef404 Avatar answered Dec 06 '25 06:12

deadbeef404