CbrRRider
CbrRRider

Reputation: 25

How to check unique bulk_create

In Django there is a method get_or_create guaranteeing the uniqueness of the object. But when records for adding a lot more 1000 processing takes a lot of time (as 1000 requests for the creation of objects). I know about bulk_create, but it does not check on the uniqueness of the input attributes of the model. How do I speed up the addition of unique objects to the database? If possible in 1 request.

Example model:

models.py

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

admin.py

# Create only one element (What I want to get)
_, created = Person.objects.get_or_create(first_name='Leon', last_name='Mariano')
_, created = Person.objects.get_or_create(first_name='Leon', last_name='Mariano')

# Create 2 objects with different ID
Person.objects.bulk_create(Person(first_name='Leon', last_name='Mariano'),
                           Person(first_name='Leon', last_name='Mariano'))

Upvotes: 1

Views: 1356

Answers (1)

CbrRRider
CbrRRider

Reputation: 25

Thanks to Ivan for the help. The solution is:

models.py

from django.db.models import UniqueConstraint

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    
    class Meta:
        constraints = [
            UniqueConstraint(fields=['first_name', 'last_name'], name='unique person')
        ]

admin.py

Person.objects.bulk_create((
    Person(first_name='fname', last_name='lname'),
    Person(first_name='fname', last_name='lname'),
    Person(first_name='fname2', last_name='lname2'),
), ignore_conflicts= True)

Upvotes: 1

Related Questions