尝试更新Djang中的记录时出现递归错误

2024-06-27 09:41:08 发布

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

我试图用信号来更新一个记录,却得到了一个“递归错误”。你知道吗

我想实现的是:当一个新的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)

Tags: djangofromimportidtruedefaultdbmodels
2条回答

是的。使用模型管理器的update()方法:

CustomUser.objects.filter(id=instance.id).update(isDevice=True)

但是您可以使用pre_save信号来代替多个数据库点击。在这种情况下,您可以在保存实例之前设置isDevice属性:

def set_is_device(sender, instance,**kwargs):
    hasSerial = len(instance.deviceSerial) 
    if hasSerial > 1:
        instance.isDevice = True
pre_save.connect(set_is_device, sender=CustomUser)

问题是您正在同一个模型对象上的post_save信号中调用.save()方法。这意味着您正在创建无止境循环,因为每次post_save调用后.save()都会触发post_save。解决方案是使用pre_save信号并在.save()调用之前修改isDevice值。基本示例:

def create_machine(sender, instance,**kwargs):
    if instance.deviceSerial:
        instance.isDevice = True #set to True
    else:
        #future code
        pass
pre_save.connect(create_machine, sender = CustomUser)

相关问题 更多 >