Saleh
Saleh

Reputation: 294

how to get a field name knowing id number in django

I have the following query set to get the subcategory name knowing the id number:

query_sc = Post_Sub_Category.objects.filter(id='1').values('sub_category_name')

it gave me the following output:

{'sub_category_name': 'car'}

how can I get only the car? I mean I need the output to be a car only 'the value not the dictionary.

Upvotes: 1

Views: 324

Answers (2)

jaap3
jaap3

Reputation: 2846

Use values_list instead of values, here's a quote straight from the docs:

A common need is to get a specific field value of a certain model instance. To achieve that, use values_list() followed by a get() call:

>>> Entry.objects.values_list('headline', flat=True).get(pk=1)
'First entry'

Upvotes: 2

Jonathan
Jonathan

Reputation: 8891

It looks like you're looking for values_list. With values_list you can get only the values, and if you want a flat list you can do the following.

Post_Sub_Category.objects.filter(id='1').values_list('sub_category_name', flat=True)

And the result will be ["car"]

Upvotes: 2

Related Questions