簡體   English   中英

Django不區分大小寫的“不同”查詢

[英]Django case insensitive “distinct” query

我正在使用這個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)

一種解決方案是使用annotate來創建具有小寫值的新字段,然后在其上使用distinct

嘗試類似的東西

from django.db.models.functions import Lower

(people.exclude(twitter_handle=None)
      .annotate(handle_lower=Lower('twitter_handle'))
      .distinct('handle_lower'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM