Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python clean()方法中的变量是';在Django省_Python_Django_Django Models - Fatal编程技术网

Python clean()方法中的变量是';在Django省

Python clean()方法中的变量是';在Django省,python,django,django-models,Python,Django,Django Models,在models.py中,我有一个带有自定义clean()方法的模型。但是,我保存在其中的任何变量都不会被存储。如果我尝试将变量保存在clean()方法之外,那么一切都会正常工作 class MenuItem(SortableMixin): item_internal = models.ForeignKey(Page, on_delete=models.CASCADE, blank=True, null=True) item_external = models.CharField(max_leng

在models.py中,我有一个带有自定义
clean()
方法的模型。但是,我保存在其中的任何变量都不会被存储。如果我尝试将变量保存在
clean()
方法之外,那么一切都会正常工作

class MenuItem(SortableMixin):
item_internal = models.ForeignKey(Page, on_delete=models.CASCADE, blank=True, null=True)
item_external = models.CharField(max_length=500000, blank=True, null=True)

def clean(self):
    if self.item_external is not None and self.item_internal is not None:
        raise ValidationError('Error')
    elif self.item_external is None and self.item_internal is None:
        raise ValidationError('Error')
    else:
        if self.item_external is not None:
            self.item_link = self.item_external
        elif self.item_internal is not None:
            self.item_link = '/' + self.item_internal.title_text.replace(' ', '%20')

项目链接中的任何内容都不会保存。为什么?如何修复它?

我试图在不创建数据库字段的情况下将某些内容保存到数据库中。解决方案很简单:

item_link = fields.CharField(max_length=50000)

我所需要做的就是将该行添加到
类中。非常感谢Willem Van Onsem,他在评论中帮助了我。谢谢

clear
clean
?可能我遗漏了什么,但是在您的示例模型中,
项链接
没有定义为字段。如果没有(数据库)字段,那么这只是对象上的一个属性,当您将其保存到数据库时,它会丢失。但是“将其保存为字符串”是什么意思?你希望它存储在哪里?@VítekPeterka:你可以在
类中构建一个字段,例如
item\u link=fields.CharField(max\u length=50000)