2π
β
You can use values_list
to extract all values of a particular field.
category_list = Article.objects.values_list('category', flat=True)
To remove duplicates from the list:
categories = list(set(category_list))
or as @Iain pointed out, you can use .distinct()
category_list = Article.objects.values_list('category', flat=True).distinct()
π€v1k45
0π
The feature you are looking for is distinct
. Since it filter in the database layer, it should be faster than filter in Python code
post_list = Article.objects.filter(category__iexact = tag).distinct()
π€Mauro Baraldi
- [Answered ]-Django Templates: How best can the output of executing python code in a Django template be suppressed?
- [Answered ]-Django: How to exclude login from accounts url?
0π
For all categories for which at least one article exists, you can do:
Category.objects.filter(article_set__isnull=False).distinct()
This will also give you a QuerySet
which you can use for further queries unlike a list
.
π€user2390182
Source:stackexchange.com