Django model distinct 的使用方法


原文:

今天突然有人問起在 django 的 model 里面怎么用 distinct, 對於這種東西,我一向的觀點是查看django 的在線文檔。於是不加思索的根據在線文檔給出了答案,但結果很讓人沮喪,運行程序時會報錯: NotImplementedError: DISTINCT ON fields is not supported by this database backend, 從字面上看,貌似是因為才用了mysql 的原因,其實不是.

django 在線文檔講解 distinct 的連接如下:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct
里面是這么講解  distinct 的

>>> Author.objects.distinct()
[...]

>>> Entry.objects.order_by('pub_date').distinct('pub_date')
[...]

>>> Entry.objects.order_by('blog').distinct('blog')
[...]

>>> Entry.objects.order_by('author', 'pub_date').distinct('author', 'pub_date')
[...]

>>> Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')
[...]

>>> Entry.objects.order_by('author', 'pub_date').distinct('author')

於是我按照這樣做了一個,結果就出現上面的錯誤了.

真正的做法是這樣的,如果用mysql 的話,distinct() 里面不要任何參數,參數應該寫在 value 中去,類似如下方式:

if __name__ == "__main__":
    a = Category.objects.values('parentcode','email').distinct()
    for obj in a:
        print obj

這表示按照 parentcode,email 組合去除重復的內容.
如果是這樣:

if __name__ == "__main__":
    a = Category.objects.values('parentcode').distinct()
    for obj in a:
        print obj

就表示按照 parentcode 去除重復的內容。  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM