我怎么能在Django bu使用信号

2024-05-21 06:17:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码

Task.objects.bulk_create(ces)

现在这是我的信号

@receiver(pre_save, sender=Task)
def save_hours(sender, instance, *args, **kwargs):
    logger.debug('test')

现在这个信号不会在批量创建中触发

我用的是django 1.8


Tags: instance密码taskobjects信号savedefcreate
2条回答

重复上面的答案:

Python2:

class CustomManager(models.Manager):
    def bulk_create(self, objs, **kwargs):
        #Your code here
        return super(models.Manager,self).bulk_create(objs,**kwargs)  

Python3:

class CustomManager(models.Manager):
    def bulk_create(self, objs, **kwargs):
        #Your code here
        return super().bulk_create(objs,**kwargs)  

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

python 2中的完整答案:

class CustomManager(models.Manager):

def bulk_create(self, objs, **kwargs):
    a = super(models.Manager,self).bulk_create(objs,**kwargs)
    for i in objs:
        post_save.send(i.__class__, instance=i, created=True)
    return a

如前所述,bulk_create不会触发这些信号-

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.

所以你必须手动触发它们。如果您希望所有模型都这样,您可以重写bulk_create,然后像这样自己发送它们-

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

那就用这个经理-

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

相关问题 更多 >