【Django】Django之ORM数据库查询获取数据操作

1、题外-POST请求接收前端传来的参数

import json

class Register(View):
    def post(self, req):
        body = json.loads(req.body)
        print(body, "body")  # {'username': '111', 'email': '111@qq.com', 'password': '111'} body
        print(body["email"]) # 1231@qq.com

2、models数据模型

# 权限
class Permissions(models.Model):
    menu = models.TextField(verbose_name='权限菜单')


# 角色
class Role(models.Model):
    title = models.CharField(verbose_name='角色名称', max_length=32)
    status = models.IntegerField(verbose_name='状态', default=0)
    permissions = models.ForeignKey(verbose_name='权限', to='Permissions', to_field='id', null=True, blank=True, on_delete=models.SET_NULL)


# 用户
class Users(models.Model):
    username = models.CharField(verbose_name='用户名', max_length=32)
    email = models.CharField(verbose_name='邮箱', max_length=64)
    password = models.CharField(verbose_name='密码', max_length=64)
    status = models.IntegerField(verbose_name='状态', default=0)
    role = models.ForeignKey(verbose_name='角色', to='Role', to_field='id', null=True, blank=True, on_delete=models.SET_NULL)

3、数据库查询

from app import models

#查询所有
doc = models.Users.objects.filter()
print(doc)  # <QuerySet [<Users: Users object (1)&gt;]&gt;

# 条件查询-当返回为空
	# filter(**args)
        doc = models.Users.objects.filter(email=body["email"])
        print(doc)  # <QuerySet []&gt;
        if not doc:
            print('查询为空')
            
	# filter(**args).values()
    	doc = models.Users.objects.filter(email=body["email"]).values()
	    print(doc)  # <QuerySet []&gt;
    	if not doc:
            print('查询为空')
	
    # filter(**args).first()
    	doc = models.Users.objects.filter(email=body["email"]).first()
	    print(doc)  # None
    	if not doc:
            print('查询为空')

# 条件查询-当返回为空
	# filter(**args)
        doc = models.Users.objects.filter(email=body["email"])
        print(doc)  # <QuerySet [<Users: Users object (1)&gt;]>
        data_dict = []  # 定义数组
        for i in doc:
            data_dict.append({  # 添加一个对象
                "id": i.id,
                "username": i.username,
                "email": i.email,
                "password": i.password,
                "status": i.status,
                "role_title": i.role.title,  # 去关联角色表查询角色名称
                "role_permissions_menu": i.role.permissions.menu  # 查询权限
            })
        print(data_dict, 'data_dict')
    	# [{'id': 1, 'username': 'admin', 'email': '13400405244@163.com', 'password': 'admin', 'status': 1, 'role_title': '超级管理员', 'role_permissions_menu': '["all_btn","all_router"]'}] data_dict
        
	# filter(**args).first()
    	doc = models.Users.objects.filter(email=body["email"]).first()
        print(doc)  # Users object (1)
        print(doc.username)  # admin
        print(doc.role.title)  # 超级管理员
        
	# filter(**args).values() 需要list一下
    	doc = list(models.Users.objects.filter(email=body["email"]).values())
        print(doc, "doc")  
        # [{'id': 1, 'username': 'admin', 'email': '13400405244@163.com', 'password': 'admin', 'status': 1, 'role_id': 1}] doc
        
        res_ls = []
        for i in doc:
            role = models.Role.objects.get(id=i["role_id"])
            print(role, "role")  # Role object (1) role
            res_ls.append({
                "id": i["id"],
                "username": i["username"],
                "email": i["email"],
                "password": i["password"],
                "status": i["status"],
                "role_title": role.title,
                "role_permissions_menu": role.permissions.menu
            })
        print(res_ls, 'res_ls')  
        # [{'id': 1, 'username': 'admin', 'email': '13400405244@163.com', 'password': 'admin', 'status': 1, 'role_title': '超级管理员', 'role_permissions_menu': '["all_btn","all_router"]'}] res_ls

	# filter(**args]).values().first()
    	doc = models.Users.objects.filter(email=body["email"]).values().first()
        print(doc)  
        # {'id': 1, 'username': 'admin', 'email': '13400405244@163.com', 'password': 'admin', 'status': 1, 'role_id': 1}
        role = models.Role.objects.get(id=doc["role_id"])
        print(role, "role")  # Role object (1) role
        data_dict = {
            "id": doc["id"],
            "username": doc["username"],
            "email": doc["email"],
            "password": doc["password"],
            "status": doc["status"],
            "role_title": role.title,
            "role_permissions_menu": role.permissions.menu
        }
        print(data_dict, 'data_dict')  
        # {'id': 1, 'username': 'admin', 'email': '13400405244@163.com', 'password': 'admin', 'status': 1, 'role_title': '超级管理员', 'role_permissions_menu': '["all_btn","all_router"]'} data_dict
        
	# all()
    	doc = models.Users.objects.all()
        print(doc)  # <QuerySet [<Users: Users object (1)>]>
        data_dict = []  # 定义数组
        for i in doc:
            data_dict.append({  # 添加一个对象
                "id": i.id,
                "username": i.username,
                "email": i.email,
                "password": i.password,
                "status": i.status,
                "role_title": i.role.title,  # 去关联角色表查询角色名称
                "role_permissions_menu": i.role.permissions.menu  # 查询权限
            })
        print(data_dict, 'data_dict')
    	# [{'id': 1, 'username': 'admin', 'email': '13400405244@163.com', 'password': 'admin', 'status': 1, 'role_title': '超级管理员', 'role_permissions_menu': '["all_btn","all_router"]'}] data_dict
        
        

原文地址:https://blog.csdn.net/CWK13400405244/article/details/130726745

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_20262.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注