gpt4 book ai didi

python - 我如何在 Django 批量创建中使用信号

转载 作者:太空狗 更新时间:2023-10-29 17:06:36 27 4
gpt4 key购买 nike

我有这个代码

Task.objects.bulk_create(ces)

现在这是我的信号

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

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

我正在使用 Django 1.8

最佳答案

如前所述,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()
....

关于python - 我如何在 Django 批量创建中使用信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30632743/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com