Django override bulk_create

拜拜、爱过 提交于 2020-08-24 07:41:03

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32809910/django-override-bulk-create

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!