Reputation: 1240
Hi I have list of model objects: my_objects
, which should be saved in a databse.
This model has order_with_respect_to
property in its Meta
class.
When I try to bulk_create
this list I got:
null value in column "_order" violates not-null constraint" during bulk_create
When I just iterate over elements and invoke save()
on every each of them. Everything is fine, but such sequential database access doesn't satisfy me...
I've tried to invoke signals.pre_save.send
function, but this didn't change the situation.
This worked when I've invoked _save_table
, on every signle element from my_objects
, but _save_table
is the heaviest part of save()
method, so I gained nothing...
Is there a possibility to save batch of django objects with only one database connection?
I'm using postgresql
.
Upvotes: 5
Views: 2829
Reputation: 483
It's just a field and you can set "_order" manually or calculate that before bulk_create.
# Model
class Product(models.Model):
name = models.CharField(max_length=255)
# Bulk create example
# Data
product_data_list = [{"name": "Apple"}, {"name": "Potato"}]
# Add "_order" field for each product
for index, product_data in enumerate(product_data_list):
product_data["_order"] = index
# Create
Product.objects.bulk_create(Product(**product_data) for product_data in product_data_list)
Upvotes: 1
Reputation: 1338
From the docs: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#bulk-create
If the model’s primary key is an AutoField it does not retrieve and set the primary key attribute, as save() does.
I am guessing that your id was on autoincrement and now it isn't being saved, which is being referenced by _order.
Upvotes: 0