我如何在Django批量创建中使用信号 [英] How can i use signals in django bulk create
问题描述
我有这个代码
Task.objects.bulk_create(ces)
现在这是我的信号
@receiver(pre_save, sender=Task)
def save_hours(sender, instance, *args, **kwargs):
logger.debug('test')
现在此信号不会在批量创建中触发
Now this signal is not triggered in bulk create
我正在使用Django 1.8
I am using django 1.8
推荐答案
如所述 bulk_create
不会触发这些信号-
As mentioned bulk_create
does not trigger these signals -
https://docs.djangoproject.com/en/1.8/ref/模型/查询集/#bulk-create
此方法将提供的对象列表插入数据库中一种高效的方式(无论有多少查询,通常只有1个查询有物体).
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).
这有很多警告:
- 将不会调用模型的save()方法,并且不会发送pre_save和post_save信号.
- 在多表继承方案中,它不适用于子模型.
- 如果模型的主键是自动字段",则它不会像save()一样检索和设置主键属性.
- 它不适用于多对多关系.
- batch_size参数控制在单个查询中创建多少个对象.默认设置是一批创建所有对象,SQLite除外,SQLite的默认值是最多999个变量使用每个查询.
因此,您必须手动触发它们.如果您希望所有模型都使用此功能,则可以覆盖 bulk_create
并将其发送给自己-
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
然后使用此管理器-
class Task(models.Model):
objects = CustomManager()
....
这篇关于我如何在Django批量创建中使用信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!