Django计算不同数量的相关模型

时间:2015-02-09 00:07:32

标签: django

考虑以下模型:

class Publisher(models.Model):
    name = models.CharField(max_length=300)
    num_awards = models.IntegerField()

class Book(models.Model):
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    publisher = models.ForeignKey(Publisher, related_name='related_books')

Publisher个实例,我怎样才能在pages字段上获得不同值的图书数量?例如:

| name      | pages | publisher |
|-----------|-------|-----------|
| Golden    | 20    | 1         |
| Grey      | 23    | 1         |
| Blue      | 20    | 1         |
| Grotesque | 27    | 2         |

如果我有publisher = Publisher.objects.get(id=1),我怎么能达到这样的目的:

# equals to 2 [Golden, Grey]
publisher.related_books.all().distinct('pages').count() 

2 个答案:

答案 0 :(得分:2)

你很亲密,你需要restrict returned values,就像这样:

publisher.related_books.all().values('pages').distinct('pages').count() 

这只会为您提供发布商不同页面长度的数量,但不会为每个页面长度提供相关的书籍。要做到这一点,你可能需要一个额外的查询。

答案 1 :(得分:2)

如果您想要可重复使用的查询,可以这样做:

class BookQuerySet(models.QuerySet):

    def by_publisher(self, publisher):
         return self.filter(publisher=publisher)

    def distinct_number_of_pages(self):
         return self.distinct(pages)

class Book(...):
    ...
    objects = BookQuerySet.as_manager()


class Publisher(...):

    @property 
    def number_of_page_lengths(self):
         return Book.objects.by_publisher(self).distinct_number_of_pages().count()