• 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)
    

    运行结果:

  • 相关阅读:
    word文档的图片怎么保存到xhEditor上
    word文档的图片怎么保存到CuteEditor上
    word文档的图片怎么保存到TinyMCE上
    word文档的图片怎么保存到eWebEditor上
    word文档的图片怎么保存到wangEditor上
    ASP.NET如何上传大文件
    JavaScript如何上传大文件
    JS如何上传大文件
    Java如何上传大文件
    JSP如何上传大文件
  • 原文地址:https://www.cnblogs.com/sch01ar/p/11324635.html
Copyright © 2020-2023  润新知