我有一个模型类,如下所示:
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 = {}
我希望能够在视图中添加search_list字典。我目前在视图中这样做:
request.user.profile.search_list['results'] = [1, 2, 3, 4, 5]
这会将它添加到每个帐户中。我怎么能这样做只有一个人的帐户?
首先,search_list
是Profile的属性,而不是User。
然而,这不会做你想要的,因为search_list
和shopping_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
程序的输出“'用户'对象没有属性'search_list'”字面上显示“用户”不是Profile类的实例,因此它无法访问其变量。