Python - Django - ORM 分组查询补充

单表查询:

models.py:

from django.db import models


class Employee(models.Model):
    name = models.CharField(max_length=16)
    age = models.IntegerField()
    salary = models.IntegerField()
    province = models.CharField(max_length=32)
    dept = models.CharField(max_length=16)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "employee"

employee 表中数据:

orm.py:

import os

if __name__ == '__main__':
    # 加载 Django 项目的配置信息
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite2.settings")
    # 导入 Django,并启动 Django 项目
    import django
    django.setup()

    from app04 import models

    from django.db.models import Avg

    # 计算每个部门的平均工资
    ret = models.Employee.objects.values("dept").annotate(avg=Avg("salary")).values("dept", "avg")
    print(ret)

运行结果:

 

连表查询:

model.py:

from django.db import models


class Employee2(models.Model):
    name = models.CharField(max_length=16)
    age = models.IntegerField()
    salary = models.IntegerField()
    province = models.CharField(max_length=32)
    dept = models.ForeignKey(to="Dept")

    def __str__(self):
        return self.name

    class Meta:
        db_table = "employee2"


class Dept(models.Model):
    name = models.CharField(max_length=16, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "dept2"

dept2 表:

employee2 表:

 

orm.py:

import os

if __name__ == '__main__':
    # 加载 Django 项目的配置信息
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite2.settings")
    # 导入 Django,并启动 Django 项目
    import django
    django.setup()

    from app04 import models

    from django.db.models import Avg

    # 连表查询计算每个部门的平均工资
    ret = models.Employee2.objects.values("dept_id").annotate(avg=Avg("salary")).values("dept__name","avg")  # 一个双下划线表示跨一张表查询
    print(ret)

运行结果:

 

posted @ 2019-08-08 23:56  Sch01aR#  阅读(486)  评论(0编辑  收藏  举报