Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.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 Django:DeferredAttribute对象/选项字段作为字符串值,用于修改基于类的ListView中的上下文_Python_Django_Django Class Based Views - Fatal编程技术网

Python Django:DeferredAttribute对象/选项字段作为字符串值,用于修改基于类的ListView中的上下文

Python Django:DeferredAttribute对象/选项字段作为字符串值,用于修改基于类的ListView中的上下文,python,django,django-class-based-views,Python,Django,Django Class Based Views,在我的模板中,我想显示一个长名称,但是,我不在数据库中保存全名,只保存一个参考号 我尝试的解决方案是将选项元组转换为字典 prd_dic = dict(PRODUCTS) 然后我用键调用字典中的值 name = prd_dic['0000'] 在我的列表视图中,我修改了上下文以将全名输入到模板中 context['product_name'] = name 当我将一个对象传递到一个位置时,需要一个字符串,并引发一个KeyError(使用DeferredAttribute对象) 我的问题是,

在我的模板中,我想显示一个长名称,但是,我不在数据库中保存全名,只保存一个参考号

我尝试的解决方案是将选项元组转换为字典

prd_dic = dict(PRODUCTS)
然后我用键调用字典中的值

name = prd_dic['0000']
在我的列表视图中,我修改了上下文以将全名输入到模板中

context['product_name'] = name
当我将一个对象传递到一个位置时,需要一个字符串,并引发一个KeyError(使用DeferredAttribute对象)

我的问题是,在视图中,是否有一个内置函数需要解决,或者作为一个函数转换并反馈到上下文中,或者直接在模型上进行转换

其思想是根据要在模板中显示的键表将保存的数字转换为全名

感谢你的一些意见

PRODUCTS = (
    ('0000'   ,   'Hamburger'),
    ('1111'   ,   'Pizza')
)

class Product(models.Model):
    product_number = models.CharField(max_length=20,choices=PRODUCTS, blank=True, null=True)

class ProductListView(ListView):
    model = Product
    template_name = 'product/product_list.html'

    def get_context_data(self, **kwargs):
        context = super(ProductListView, self).get_context_data(**kwargs)
        prd_obj = Product.product_number # this is an object
        prd_dic = dict(PRODUCTS)
        name = prd_dic[prd_obj] # a single string, prd_dic['0000'] works in template
        context['product_name'] = name
        return context

自动为您定义方法
get\u product\u number\u display
;您可以直接从模板调用它,而无需覆盖
get\u context\u data