尝试在Django

时间:2018-10-13 13:42:00

标签: python django

我正在尝试使用信号来更新记录,并遇到“递归错误”。

我要实现的目标:将新的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)

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

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

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)
相关问题