Django ORM in Django ORM bulk operations in batch operations

Django ORM in batch operation

 

Data model definition

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=10, decimal_places=2)

Bulk insert data

Bulk insert data, the first to create a list of objects , and then call bulk_create method, once the data is inserted in the list to the database.

product_list_to_insert = list()
for x in range(10):
    product_list_to_insert.append(Product(name='product name ' + str(x), price=x))
Product.objects.bulk_create(product_list_to_insert)

Batch update data

When the batch update data, data filtering first, and then call the update method for a one-time update. The following statement will generate a similar update .... frrom .... SQL statement.

Product.objects.filter(name__contains='name').update(name='new name')

Batch delete data

When the batch update data, data filtering first, and then call the delete method to delete a one-time. The following statement speaks generate similar delete from ... where ... SQL statement.

Product.objects.filter(name__contains='name query').delete()

 

 
 
 

Data model definition

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=10, decimal_places=2)

Bulk insert data

Bulk insert data, the first to create a list of objects , and then call bulk_create method, once the data is inserted in the list to the database.

product_list_to_insert = list()
for x in range(10):
    product_list_to_insert.append(Product(name='product name ' + str(x), price=x))
Product.objects.bulk_create(product_list_to_insert)

Batch update data

When the batch update data, data filtering first, and then call the update method for a one-time update. The following statement will generate a similar update .... frrom .... SQL statement.

Product.objects.filter(name__contains='name').update(name='new name')

Batch delete data

When the batch update data, data filtering first, and then call the delete method to delete a one-time. The following statement speaks generate similar delete from ... where ... SQL statement.

Product.objects.filter(name__contains='name query').delete()

 

Guess you like

Origin www.cnblogs.com/taosiyu/p/11248441.html