简体   繁体   English

在post_save信号中使用Python深度复制吗?

[英]Python deepcopy in a post_save signal?

The following code is in a Django signal and when the number of copies is '2', the following code creates 80+ copies and then crashes...What's wrong? 以下代码在Django信号中,当副本数为'2'时,以下代码创建80多个副本,然后崩溃...出了什么问题?

def internal_signal(sender, instance, signal, created, *args, **kwargs):
       for i in range(instance.number_of_copies):
            item_copy = deepcopy(instance)
            item_copy.id = item_copy.id + 1
            item_copy.internal_barcode = "%s"%(item_copy.item_location.location_code)
            item_copy.save()

post_save.connect(internal_signal, sender=Inventory)

Thanks. 谢谢。

Edit: Duh! 编辑:Du! Found the issue, the above code was part of post_save operation of a Django signal, so every 'save' triggers another loop and then heap crash. 发现了问题,上面的代码是Django信号的post_save操作的一部分,因此每个“保存”都会触发另一个循环,然后导致堆崩溃。

What is the best way to create 'n' objects and save it in Django programatically? 创建'n'对象并将其以编程方式保存在Django中的最佳方法是什么?

This is my test code,it performanced as expected . 这是我的测试代码,性能符合预期。 I think you should make a unit test to find where the problem is. 我认为您应该进行单元测试以查找问题所在。 Leave Django alone! 独自离开Django!

class T:
    def save(this):
        pass
from copy import deepcopy
from copy import copy
instance = T() 
instance.number_of_copies = 2
instance.id = 1 
instance.item_location=T()
instance.item_location.location_code = 2 
for i in range(instance.number_of_copies):
    item_copy = deepcopy(instance)
    item_copy.id = item_copy.id + 1 
    item_copy.internal_barcode = "%s"%(item_copy.item_location.location_code)
    item_copy.save()
    print " id,code:",item_copy.id,item_copy.internal_barcode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM