简体   繁体   中英

Django: Get one key and value from queryset dictionary

I have this query: item = Item.objects.filter(id=3)

It is returning a queryset with its the keys and values. Now I need to extract a particular value from the queryset, like this:

item_name = item['name']

But it does not work. How can I achieve this? Send the most simple way if possible, please. Thanks!

You have several wrong assumptions here.

A queryset is not a dict and does not have keys and values. It's a sequence of items, if anything most similar to a list.

I think what you want to do is to get a specific instance from the database, and access its fields. To get one instance you use get , not filter , as filter will always give you a queryset even if there is only a single match. Then, from that instance, you use attribute access not dict lookup. So:

item = Item.objects.get(id=3)
item_name = item.name

Here you can use the getattr function of python through which you can get your objective.

getattr(item, 'name')

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