码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-05-05 11:15:33      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:use   erb   tde   datetime   settings   net   module   print   col   

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‘}]>

 

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

标签:use   erb   tde   datetime   settings   net   module   print   col   

原文地址:https://www.cnblogs.com/zh-xiaoyuan/p/12829652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!