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.usernameclass 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

相关推荐