Django Query sort case-insensitive using Model method with PostgreSQL

前端 未结 2 1313
庸人自扰
庸人自扰 2020-12-19 13:35

I\'m really new to django, python and postgres... I can\'t seem to find the answer on how to order_by being case insensitive while using Model as the query method, only if y

相关标签:
2条回答
  • 2020-12-19 13:52

    Using QuerySet.extra(select=...):

    @classmethod
    def get_channel_list(cls, account):
        ret = cls.objects.extra(select={'name_lower': 'lower(name)'})
        ret = ret.order_by('-name_lower')
        ret = ret.filter(accountid=account).values_list('name', 'channelid')
        return channels
    
    0 讨论(0)
  • 2020-12-19 13:58

    With django 1.8, there is a built-in solution:

    from django.db.models.functions import Lower
    ...
    ret = ret.order_by(Lower('name_lower'))
    ret = ret.order_by(Lower('name_lower').asc())
    ret = ret.order_by(Lower('name_lower').desc())
    
    0 讨论(0)
提交回复
热议问题