from django.db import models classPerson(models.Model): """Person""" id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) age = models.IntegerField() birthday = models.DateField(verbose_name="生日") country = models.CharField(max_length=20)
classBook(models.Model): """Book表""" id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) author = models.ForeignKey(Person, verbose_name="作者", on_delete=models.DO_NOTHING, related_name="person_writed") type = models.CharField(verbose_name="类别", max_length=30, blank=True) price = models.IntegerField() published_date = models.DateField(verbose_name="出版日期", auto_now=False, auto_now_add=False) def__str__(self): return self.name
from django.db.models import Avg,Count,Min,Max,Sum # 统计所有书籍的平均售价 result = Book.objects.all().aggregate(Avg('price')) # 统计所有作者中,小于40岁的人数 result = Person.objects.filter(age__lte=40).aggregate(count('id')) # 统计金庸出版书籍的最高价格 result = Book.objects.filter(author__name='金庸').aggregate(Max('price')) # 统计购买所有金庸出版的书籍多少钱 result = Book.objects.filter(author__name='金庸').aggregate(Sum('price'))