[英]How to use value from dictionary returned by QuerySet in Django
I wrote this query 我写了这个查询
p_name = OrderLine.objects.filter(order_id=order).values('product_name')
and it is returning the following results 它返回以下结果
<QuerySet [{'product_name': 'doc 1 (1-1000)'}]>
I want to use only doc 1 (1-1000)
as a string. 我只想使用
doc 1 (1-1000)
作为字符串。 Is there a method for this. 有没有办法做到这一点。 I read on some website to use
.values()
but is returning [{'product_name': 'doc 1 (1-1000)'}]
我在某个网站上阅读过使用
.values()
但返回的是[{'product_name': 'doc 1 (1-1000)'}]
You could use values_list()
+ flat=True
to generate a list instead. 您可以使用
values_list()
+ flat=True
来生成列表。
>>> p_name = OrderLine.objects.filter(order_id=order).values_list('product_name',flat=True)
>>> print(p_name)
>>> <QuerySet ['doc 1 (1-1000)']>
This is meant to generate a list of values from the field passed in value_list()
. 这旨在从在
value_list()
传递的字段中生成值列表。 In case you are sure that this will have only one value and it's the one wanted, you may index the item in the list: 如果您确定它只有一个值并且是想要的值,则可以在列表中为该项目建立索引:
>>> p_name[0]
>>> 'doc 1 (1-1000)'
I agree with @Lemayzeur answer. 我同意@Lemayzeur的答案。 But you can also use the code as you have it, in two ways:
但是,您也可以通过两种方式使用代码:
p_name.first() # this will return the dictionary itself
Or you can convert the queryset into a list using 或者您可以使用以下命令将查询集转换为列表
list(p_name)
It's not the recommended way, but it may come handy in other situations. 这不是推荐的方法,但是在其他情况下可能会派上用场。
Cheers! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.