Malik A. Rumi
Malik A. Rumi

Reputation: 2015

Django - Get Value Only from queryset

When the docs discuss values() and values_list(), or any query for that matter, they always require that you know what you are looking for, i.e.,

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

What about the situation where you need a value from a specific field, whether on this model or a foreign key, but you don't know the pk or the value in the specified field, and you don't care, you just need whatever is there. How do you query for it?

Alternatively, if I use this example from the docs:

>>> Entry.objects.values_list('id', flat=True).order_by('id')
<QuerySet [1, 2, 3, ...]>

Could I add slice notation to the end of the query? But even then, I might not know in advance which slice I need. In other words, how to dynamically get a value from a specified field without knowing in advance what it or its pk is? Thx.

Upvotes: 0

Views: 9123

Answers (1)

Evhz
Evhz

Reputation: 9238

Depending your scenario (this time a simple query) you have many of options to do it. One is to use a variable as field name. Then, feed that variable dynamically:

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

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

In order to slice results use offset/limit as follows:

Entry.objects.all()[offset:limit]

>>> field='headline'
>>> Entry.objects.values_list(field, flat=True)[5:10]

Upvotes: 3

Related Questions