• ORM基于对象的查询和基于Queryset的查询


    1 models.py

    from django.db import models
    
    # Create your models here.
    
    from django.contrib.auth.models import AbstractUser
    
    class UserInfo(AbstractUser):
        """
        用户信息表
        """
        nid = models.AutoField(primary_key=True)
        phone = models.CharField(max_length=11, null=True, unique=True)
        avatar = models.FileField(upload_to="avatars/", default="avatars/default.png", verbose_name="头像")
        create_time = models.DateTimeField(auto_now_add=True)
    
        blog = models.OneToOneField(to="Blog", to_field="nid", null=True)
    
        def __str__(self):
            return self.username

    class Article(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=50, verbose_name="文章标题") # 文章标题 desc = models.CharField(max_length=255) # 文章描述 create_time = models.DateTimeField() # 创建时间 user = models.ForeignKey(to="UserInfo", to_field="nid")    def __str__(self): return self.username

    查询

    import os
    
    
    if __name__ == '__main__':
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bbs.settings")
    
        import django
        django.setup()
    
        from blog import models
    
        # 基于对象的查询 SQL: 子查询
        a1 = models.Article.objects.first()
        print(a1.user, type(a1.user))
        #xiaohei <class 'blog.models.UserInfo'>
    
        print(a1.user.username)
        #xiaohei
    
        print(a1.user.avatar)
        # avatars/picture_iHCkQGi.png
    
    
        # 基于QuerySet查询, SQL: join连表查询
        a2 = models.Article.objects.filter(pk=1)
        print(a2.values("user"),type(a2.values("user")))
        # <QuerySet [{'user': 5}]>     <class 'django.db.models.query.QuerySet'>
    
        print(a2.values("user__avatar"))
        # <QuerySet [{'user__avatar': 'avatars/picture_iHCkQGi.png'}]>
  • 相关阅读:
    分享ASP.NET+jQuery MiniUI后台购物管理
    ASP.NET发送电子邮件
    LINQ学习(三):Where子句
    ASP.NET配置KindEditor文本编辑器
    一步步写自己SqlHelper类库(五):Command对象
    ASP.NET生成静态页面的简单实现
    兼职开发悟出的点点滴滴
    设计模式学习笔记
    if else替代者
    ASP.NET 一生命周期中的额事件
  • 原文地址:https://www.cnblogs.com/zh-xiaoyuan/p/12829652.html
Copyright © 2020-2023  润新知