📜  django createmany - Python (1)

📅  最后修改于: 2023-12-03 15:30:28.524000             🧑  作者: Mango

Django CreateMany

Django CreateMany is a useful tool for quickly creating multiple instances of a model at once. It can save a lot of time and effort, especially when dealing with large amounts of data.

To use create_many, you'll need to install the django-bulk-create package:

pip install django-bulk-create

Once installed, you can use create_many on any model that inherits from django.db.models.Model. Here's an example:

from django_bulk_create import BulkCreateManagerMixin


class MyModel(BulkCreateManagerMixin, models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    ...

data = [
    {'name': 'John', 'age': 23, ...},
    {'name': 'Jane', 'age': 29, ...},
    {'name': 'Bob', 'age': 31, ...},
    ...
]

MyModel.objects.create_many(data)

Note that the data argument should be a list of dictionaries, where each dictionary represents the data for one instance of the model.

Also, make sure to include the BulkCreateManagerMixin in your model to enable the create_many method.

create_many is much faster than creating each instance individually, as it only performs a single INSERT statement on the database. This can make a big difference when dealing with large amounts of data.

Overall, django-create-many is a useful tool for quickly creating multiple instances of a model. By leveraging the power of django-bulk-create, you can optimize your data creation process and save precious time.