简体   繁体   English

Django,从模型获取属性

[英]Django, get an attribute from a model

I'm trying to get the value of a field from a model. 我正在尝试从模型中获取字段的值。 The thing is that I'm getting the id if I use filter(pk=university) . 问题是,如果我使用filter(pk=university) ,我将获得id But what it returns is [{'name': u'Icecream Chocolate'}] . 但是它返回的是[{'name': u'Icecream Chocolate'}] Is it possible to get its name without the [{'name': u' ... }] ? 是否可以不使用[{'name': u' ... }]来获得其名称?

item_name = Icecream.objects.filter(pk=icecream_id).values('name')

One option is to use objects.get() : 一种选择是使用objects.get()

item_name = Icecream.objects.get(pk=icecream_id).name

Or, if you still want to use filter() , but don't want to see dictionary with name key, use values_list() with flat=True : 或者,如果您仍然想使用filter() ,但又不想看到带有name键的字典,请使用带有flat=True values_list()

item_name = Icecream.objects.get(pk=icecream_id).values_list('name', flat=True)

从文档的下一部分开始:

item_name = Icecream.objects.filter(pk=icecream_id).values_list('name')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM