Django中使用group_by的方法

WBOY
Release: 2016-06-06 11:17:53
Original
1845 people have browsed it

本文实例讲述了Django中使用group_by的方法。分享给大家供大家参考。具体分析如下:

在Django中怎样使用group_by语句呢?找了很多资料,都没有看到好的,在这里分享两种方法给大家:

首先,我们先建一个简单的模型。

class Book(models.Model): 
   name = models.CharField(u'书名',max_length=255,db_index = True) 
   author = models.CharField(u'作者',max_length=255) 
   remark = models.CharField(u'备注',max_length=255) 
   pub_date = models.DateTimeField(u'发表时间',auto_now_add = True) 

Copy after login

方式一:

book_list = Book.objects.all() 
book_list.query.group_by = ['author'] 

Copy after login

方式二:

query = Book.objects.all().query 
query.group_by = ['author'] 
book_list = QuerySet(query = query, model = Book) 

Copy after login

不过,本人在实际应用中发现一个小小的问题:

如果author字段有空值的话,用方式一会报错,用方式二木有问题。

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template