zoukankan      html  css  js  c++  java
  • Python

    单表查询:

    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)
    

    运行结果:

  • 相关阅读:
    配置JAVA的环境变量
    Navicat Premium v12.0.23.0 安装,使用激活码激活
    mysql 5.7.33安装教程
    查看mysql服务
    postman测试post请求参数是List entity后端用@RequestBody接受lIst entity方式
    最简单的MySQL安装教程(数据库免安装版,免安装版,亲测好用) mysql-5.7.33-winx64.zip
    mysql数据库安装5.7.33
    java删除附件图片
    java生成条形码
    最高的牛
  • 原文地址:https://www.cnblogs.com/sch01ar/p/11324635.html
Copyright © 2011-2022 走看看