Say your model is 'Shop'
class Shop(models.Model):
street = models.CharField(max_length=150)
city = models.CharField(max_length=150)
# some of your models may have explicit ordering
class Meta:
ordering = ('city',)
Since you may have the Meta
class ordering
attribute set (which is tuple or a list), you can use order_by()
without parameters to clear any ordering when using distinct()
. See the documentation under order_by
()
If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters.
and distinct()
in the note where it discusses issues with using distinct()
with ordering.
To query your DB, you just have to call:
models.Shop.objects.order_by().values('city').distinct()
It returns a dictionary
or
models.Shop.objects.order_by().values_list('city').distinct()
This one returns a ValuesListQuerySet
which you can cast to a list
.
You can also add flat=True
to values_list
to flatten the results.
See also: Get distinct values of Queryset by field
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…