我查询一个模型:
Members.objects.all()
它返回:
Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop
我想要的是知道Django最好的点火方式
对我的数据库进行group_by查询,如:
Members.objects.all().group_by('designation')
当然,这是行不通的。
我知道我们可以在django/db/models/query.py上做一些技巧,但我只是好奇如何不打补丁就能做到。
下面的模块允许你对Django模型进行分组,并且仍然使用结果中的QuerySet: https://github.com/kako-nawao/django-group-by
例如:
from django_group_by import GroupByMixin
class BookQuerySet(QuerySet, GroupByMixin):
pass
class Book(Model):
title = TextField(...)
author = ForeignKey(User, ...)
shop = ForeignKey(Shop, ...)
price = DecimalField(...)
class GroupedBookListView(PaginationMixin, ListView):
template_name = 'book/books.html'
model = Book
paginate_by = 100
def get_queryset(self):
return Book.objects.group_by('title', 'author').annotate(
shop_count=Count('shop'), price_avg=Avg('price')).order_by(
'name', 'author').distinct()
def get_context_data(self, **kwargs):
return super().get_context_data(total_count=self.get_queryset().count(), **kwargs)
“本书/ books.html”
<ul>
{% for book in object_list %}
<li>
<h2>{{ book.title }}</td>
<p>{{ book.author.last_name }}, {{ book.author.first_name }}</p>
<p>{{ book.shop_count }}</p>
<p>{{ book.price_avg }}</p>
</li>
{% endfor %}
</ul>
与注释/聚合基本Django查询的区别在于使用了相关字段的属性,例如book.author.last_name。
如果您需要已经分组在一起的实例的pk,请添加以下注释:
.annotate(pks=ArrayAgg('id'))
注意:ArrayAgg是Postgres特定的函数,从Django 1.9开始可用:https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/aggregates/#arrayagg
下面的模块允许你对Django模型进行分组,并且仍然使用结果中的QuerySet: https://github.com/kako-nawao/django-group-by
例如:
from django_group_by import GroupByMixin
class BookQuerySet(QuerySet, GroupByMixin):
pass
class Book(Model):
title = TextField(...)
author = ForeignKey(User, ...)
shop = ForeignKey(Shop, ...)
price = DecimalField(...)
class GroupedBookListView(PaginationMixin, ListView):
template_name = 'book/books.html'
model = Book
paginate_by = 100
def get_queryset(self):
return Book.objects.group_by('title', 'author').annotate(
shop_count=Count('shop'), price_avg=Avg('price')).order_by(
'name', 'author').distinct()
def get_context_data(self, **kwargs):
return super().get_context_data(total_count=self.get_queryset().count(), **kwargs)
“本书/ books.html”
<ul>
{% for book in object_list %}
<li>
<h2>{{ book.title }}</td>
<p>{{ book.author.last_name }}, {{ book.author.first_name }}</p>
<p>{{ book.shop_count }}</p>
<p>{{ book.price_avg }}</p>
</li>
{% endfor %}
</ul>
与注释/聚合基本Django查询的区别在于使用了相关字段的属性,例如book.author.last_name。
如果您需要已经分组在一起的实例的pk,请添加以下注释:
.annotate(pks=ArrayAgg('id'))
注意:ArrayAgg是Postgres特定的函数,从Django 1.9开始可用:https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/aggregates/#arrayagg
还可以使用regroup模板标记按属性分组。从文档中可以看出:
cities = [
{'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
{'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
{'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
{'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
{'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]
...
{% regroup cities by country as countries_list %}
<ul>
{% for country in countries_list %}
<li>{{ country.grouper }}
<ul>
{% for city in country.list %}
<li>{{ city.name }}: {{ city.population }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
看起来是这样的:
印度
孟买:19000000
加尔各答:15000000
美国
纽约:2000万
芝加哥:7000000
日本
东京:33000000
我相信它也适用于QuerySets。
来源:https://docs.djangoproject.com/en/2.1/ref/templates/builtins/重组
编辑:请注意,如果字典列表没有按键排序,regroup标记就不能正常工作。它是迭代工作的。因此,在将石斑鱼的键传递给regroup标记之前,对列表(或查询集)进行排序。
文档说您可以使用值来对查询集进行分组。
class Travel(models.Model):
interest = models.ForeignKey(Interest)
user = models.ForeignKey(User)
time = models.DateTimeField(auto_now_add=True)
# Find the travel and group by the interest:
>>> Travel.objects.values('interest').annotate(Count('user'))
<QuerySet [{'interest': 5, 'user__count': 2}, {'interest': 6, 'user__count': 1}]>
# the interest(id=5) had been visited for 2 times,
# and the interest(id=6) had only been visited for 1 time.
>>> Travel.objects.values('interest').annotate(Count('user', distinct=True))
<QuerySet [{'interest': 5, 'user__count': 1}, {'interest': 6, 'user__count': 1}]>
# the interest(id=5) had been visited by only one person (but this person had
# visited the interest for 2 times
你可以找到所有的书,并按名字分组:
Book.objects.values('name').annotate(Count('id')).order_by() # ensure you add the order_by()
你可以在这里看一些小抄。