Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django override bulk_create

How to override bulk_create method? I try this

class SomeModel(models.Model):
    field = models.CharField()

    def bulk_create(self, objs, batch_size=None):
        #do something
        return super(SomeModel, self).bulk_create(objs, batch_size)

But it doesn't work. When I run this code

SomeModel.objects.bulk_create(objects_list)

It's create new objects, but it doesn't use my override bulk_create method. Is it possible to override bulk_create? And how?

like image 665
Dima Kudosh Avatar asked Sep 27 '15 16:09

Dima Kudosh


People also ask

How do I override a save in Django?

save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically.

How Django knows to update VS insert?

The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.

What is __ str __ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.


1 Answers

bulk_create is a method on the Manager class, and SomeModel.objects is an instance of Manager. You need to subclass Manager and override the method there, then add the manager to SomeModel:

class SomeModelManager(models.Manager):
    def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):
        ...

class SomeModel(models.Model):
    objects = SomeModelManager()

See the documentation on custom managers for more information.

like image 185
knbk Avatar answered Sep 18 '22 06:09

knbk