Select distinct values from a table field

前端 未结 3 1420
小鲜肉
小鲜肉 2020-12-12 12:44

I\'m struggling getting my head around the Django\'s ORM. What I want to do is get a list of distinct values within a field on my table .... the equivalent of one of the fol

3条回答
  •  半阙折子戏
    2020-12-12 13:19

    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, 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 dictionnary

    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

提交回复
热议问题