我试图用信号来更新一个记录,却得到了一个“递归错误”。你知道吗
我想实现的是:当一个新的customUser被保存到数据库中时,我想看看用户是否在deviceSerial字段中输入了一个序列号。如果有序列号,我想将“isDevice”设置为True,因为它默认为false。 当我使用.save()时,问题似乎出现了。我假设我需要使用某种类型的更新命令?你知道吗
错误消息:
Exception Type: RecursionError
Exception Value: maximum recursion depth exceeded
Exception Location:
C:\Users\matth\AppData\Local\Programs\Python\Python36\lib\copyreg.py in __newobj__, line 88
Python Executable:
C:\Users\matth\AppData\Local\Programs\Python\Python36\python.exe
我的型号.py:
from django.db import models
from django.conf import settings
from defaults.models import DefaultDMLSProcessParams
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from django.db.models.signals import pre_save
from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location='/media/photos')
class CustomUser(AbstractUser):
customerTag = models.CharField(max_length=50,)
isAdmin = models.BooleanField(default = False,)
isDevice = models.BooleanField(default = False,)
notifications = models.BooleanField(default = True,)
deviceSerial= models.CharField(max_length=50,)
equipmentName= models.CharField(max_length=50,default=(str(equipment)+str(id)),)
equipmentDescription = models.CharField(max_length=200,)
image = models.ImageField(storage=fs, blank = True)
def create_machine(sender, instance,**kwargs):
hasSerial = len(instance.deviceSerial)
if hasSerial >1:
newRecordID = instance.id #grab id of record that was just saved
newRecord = CustomUser.objects.get(id=newRecordID) #get object
newRecord.isDevice = True #set to True
newRecord.save(update_fields=['isDevice']) #save it
else:
#future code
pass
post_save.connect(create_machine, sender = CustomUser)
是的。使用模型管理器的
update()
方法:但是您可以使用
pre_save
信号来代替多个数据库点击。在这种情况下,您可以在保存实例之前设置isDevice
属性:问题是您正在同一个模型对象上的
post_save
信号中调用.save()
方法。这意味着您正在创建无止境循环,因为每次post_save
调用后.save()
都会触发post_save
。解决方案是使用pre_save
信号并在.save()
调用之前修改isDevice
值。基本示例:相关问题 更多 >
编程相关推荐