Django Group对象的外键字段值

时间:2020-10-23 08:33:01

标签: 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("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 = Books.objects.all().filter(publisher=1).group_by('category')

输出类似

[
{ category 1: [book1, book2, ...] },
{ category 2: [book3, book4,... ] },
 ]

谁能告诉我,我该如何实现?

谢谢。

1 个答案:

答案 0 :(得分:0)

我假设您要对数据进行一些汇总(例如计数或总和)。为此,您可以使用类似的

from django.db.models import Count

books = Books.objects.all().filter(publisher=1).values('category').annotate(Count('id'))

这将按category对数据进行分组,并根据每个组对您的图书ID进行计数。您还可以阅读有关注释here的更多信息。

相关问题