简体   繁体   中英

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. Is there a method for this. I read on some website to use .values() but is returning [{'product_name': 'doc 1 (1-1000)'}]

You could use values_list() + flat=True to generate a list instead.

>>> 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() . 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. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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