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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With