Django按外键字段值对对象进行分组
我想按出版商和类别对所有图书对象进行筛选。例如Django按外键字段值对对象进行分组,django,rest,django-rest-framework,Django,Rest,Django Rest Framework,我想按出版商和类别对所有图书对象进行筛选。例如 class Publisher(models.Model): name = CICharField("Name", max_length=200, unique=True) description = models.TextField("Description", blank=True) class Category(models.Model): name = CICharField
class Publisher(models.Model):
name = CICharField("Name", max_length=200, unique=True)
description = models.TextField("Description", blank=True)
class Category(models.Model):
name = CICharField("Name", max_length=200, unique=True)
description = models.TextField("Description", blank=True)
class Book(models.Model):
name = CICharField("Name", max_length=200, unique=True)
description = models.TextField("Description", blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="books", blank=True, null=True)
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, related_name="books", blank=True, null=True)
输出可能是这样的
books = Books.objects.all().filter(publisher=1).group_by('category')
谁能告诉我,我如何才能做到这一点
谢谢。我假设您希望对数据进行一些聚合(例如计数或求和)。为此,您可以使用
[
{ category 1: [book1, book2, ...] },
{ category 2: [book3, book4,... ] },
]
它将按类别对您的数据进行分组
,并根据每组统计您的图书ID。您还可以阅读有关注释的更多信息
from django.db.models import Count
books = Books.objects.all().filter(publisher=1).values('category').annotate(Count('id'))