Ryan Oh
Ryan Oh

Reputation: 647

How do I only get values from Django queryset?

So I have a filtered QuerySet with a specific field, that looks like this:
[{'category':'book'}, {'category':'food'}, {'category':'movie'}, {'category':'book'}, {'category':'style'}, ...].
I now want to make a list that only contains the values(book, food, movie, style), with no duplicates. How do I make it possible? Thanks. :)

Upvotes: 1

Views: 1232

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You add .distinct() on it to retrieve the value only once. Furthermore instead of using .values('category'), you can use .values_list('category', flat=True) to obtain a collection that only contains the categories.

So the queryset should look like:

SomeModel.objects.values_list('category', flat=True).distinct()

That being said, based on how you retrieve data, it looks like you have data duplication. You for example store the name of a category, instead of making a Category model and link to that category.

Upvotes: 1

Related Questions