How to get all values for a certain field in django ORM?

Question:

I have a table called user_info. I want to get names of all the users. So the table has a field called name. So in sql I do something like

SELECT distinct(name) from user_info

But I am not able to figure out how to do the same in django. Usually if I already have certain value known, then I can do something like below.

user_info.objects.filter(name='Alex')

And then get the information for that particular user.

But in this case for the given table, I want to get all the name values using django ORM just like I do in sql.

Here is my django model

class user_info(models.Model):
    name = models.CharField(max_length=255)
    priority = models.CharField(max_length=1)
    org = models.CharField(max_length=20)

How can I do this in django?

Asked By: Souvik Ray

||

Answers:

You can use values_list.

user_info.objects.values_list('name', flat=True).distinct()

Note, in Python classes are usually defined in InitialCaps: your model should be UserInfo.

Answered By: Daniel Roseman

You can use values_list() as given in Daniel’s answer, which will provide you your data in a list containing the values in the field. Or you can also use, values() like this:

user_info.object.values('name')

which will return you a queryset containing a dictionary. values_list() and values() are used to select the columns in a table.

Answered By: Rabin Lama Dong

Adding on to the accepted answer, if the field is a foreign key the id values(numerical) are returned in the queryset. Hence if you are expecting other kinds of values defined in the model of which the foreign key is part then you have to modify the query like this:

    `Post.objects.values_list('author__username')` 

Post is a model class having author as a foreign key field which in turn has its username field:
Here, "author" field was appended with double undersocre followed by the field "name", otherwise primary key of the model will be returned in queryset. I assume this was @Carlo’s doubt in accepted answer.

Answered By: azzam
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.