Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - bulk_create objects with order_with_respect_to attribute

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.

like image 408
Jakub Kuszneruk Avatar asked Nov 09 '22 06:11

Jakub Kuszneruk


1 Answers

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)
like image 191
stefanitsky Avatar answered Nov 14 '22 21:11

stefanitsky