python – Django不区分大小写的“不同”查询

我正在使用这个
django查询

people.exclude(twitter_handle=None).distinct('twitter_handle').values_list('twitter_handle', flat=True)

我的独特查询返回两个对象
例如 :

['Abc','abc']

如何获得不区分大小写的结果?就像在这种情况下一样

['abc']

使用django 1.9.6,
python 2.7

最佳答案 你可以使用
.annotate()
Func() expressions在小写的twitter_handle值上应用.distinct():

>>> from django.db.models.functions import Lower
>>> people.order_by().exclude(twitter_handle=None).annotate(handle_lower=Lower("twitter_handle")).distinct("handle_lower")

您不能将values_list(‘twitter_handle’,flat = True)附加到上述查询,因为您不能对values_list中不存在的字段应用distinct,因此您必须自己执行:

 >>> queryset = people.order_by().exclude(twitter_handle=None).annotate(handle_lower=Lower("twitter_handle")).distinct("handle_lower")
 >>> [p.twitter_handle for p in queryset]

或者您可以获得小写的twitter_handle值:

>>> people.order_by().exclude(twitter_handle=None).annotate(handle_lower=Lower("twitter_handle")).distinct("handle_lower").values_list("handle_lower", flat=True)
点赞