[TimLinux] django aggregate和annotate示例

1. 聚合与注解

聚合(aggregate)比较好理解,注解(annotate)真不好理解,这篇示例参考了文章“django中聚合aggregate和annotate GROUP BY的使用方法”提供的模型,以及部分内容。根据参考的文章,注解的理解是:在聚合的基础上使用了GROUP BY语句。

2. 模型代码

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

    class Meta:
        db_table = 'author'


class Publisher(models.Model):
    name = models.CharField(max_length=300)
    num_awards = models.IntegerField()
    
    class Meta:
        db_table = 'publisher'


class Book(models.Model):
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    rating = models.FloatField()
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
    pubdate = models.DateField()

    class Meta:
        db_table = 'book'


class Store(models.Model):
    name = models.CharField(max_length=300)
    books = models.ManyToManyField(Book)
    registered_users = models.PositiveIntegerField()

    class Meta:
        db_table = 'store'

3. aggregate

ttt

4. annotate

ttt

猜你喜欢

转载自www.cnblogs.com/timlinux/p/9232348.html