How can i use signals in django bulk create

前端 未结 2 787
甜味超标
甜味超标 2021-02-05 06:31

I have this code

Task.objects.bulk_create(ces)

Now this is my signal

@receiver(pre_save, sender=Task)
def save_hours(sender, instanc         


        
2条回答
  •  梦如初夏
    2021-02-05 06:50

    As mentioned bulk_create does not trigger these signals -

    https://docs.djangoproject.com/en/1.8/ref/models/querysets/#bulk-create

    This method inserts the provided list of objects into the database in an efficient manner (generally only 1 query, no matter how many objects there are).

    This has a number of caveats though:

    • The model’s save() method will not be called, and the pre_save and post_save signals will not be sent.
    • It does not work with child models in a multi-table inheritance scenario.
    • If the model’s primary key is an AutoField it does not retrieve and set the primary key attribute, as save() does.
    • It does not work with many-to-many relationships.
    • The batch_size parameter controls how many objects are created in single query. The default is to create all objects in one batch, except for SQLite where the default is such that at most 999 variables per query are used.

    So you have to trigger them manually. If you want this for all models you can override the bulk_create and send them yourself like this -

    class CustomManager(models.Manager):
        def bulk_create(items,....):
             super().bulk_create(...)
             for i in items:
                  [......] # code to send signal
    

    Then use this manager -

    class Task(models.Model):
        objects = CustomManager()
        ....
    

提交回复
热议问题