Django: Get one key and value from queryset dictionary

Question:

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!

Asked By: Gonzalo Dambra

||

Answers:

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
Answered By: Daniel Roseman

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

getattr(item, 'name')
Answered By: Shahabaz Alam