如何在djang的model类中编辑变量

2024-05-16 14:06:57 发布

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

我有一个模型类,如下所示:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    #basket = {'list':['1']}
    search_list = {}
    shopping_basket = {}

我想能够在视图中添加到搜索列表字典。我目前正在视图中执行此操作:

request.user.profile.search_list['results'] = [1, 2, 3, 4, 5]

不过,这会把它加到每个人的账户上。我怎么能这样做,它只是一个人的帐户


Tags: 模型视图truesearchmodelmodelsprofilelength
2条回答

首先,search_list是概要文件的属性,而不是用户

但是这并不能满足您的需要,因为search_listshopping_basket是类属性,因此将由所有配置文件共享。不要这样做

要存储任意数据,请使用会话

要访问search_list变量,需要使用正确的实例名。举个例子:

class Example:
    example_dict = {}


example = Example() # Here you are creating instance of the class Example
example.example_dict = {something} # Then you are accessing variable within the instance of the class
print(example.example_dict) # and printing it

程序的输出“'User'object has no attribute'search\u list'”字面上表示“User”不是Profile类的实例,因此它无权访问其变量

相关问题 更多 >