chatGPT说明SQLAlchemy中的关系加载技术,joinedload加载方式,并与selectinload的不同之处

之前一直对SQLAlchemy中的关系加载很模糊
一次百度在SQLAlchemy中如何加载关联数据,给出的答案是selectinload,发现蛮好用,就一直使用了,没再继续了解其他的关系API,一次偶然的技术需要到这些了,赶紧来复习一下

官方文档:

关系加载技术:https://www.osgeo.cn/sqlalchemy/orm/loading_relationships.html

关系加载器API:https://www.osgeo.cn/sqlalchemy/orm/loading_relationships.html?highlight=selectinload#relationship-loader-api

请添加图片描述

案例

以下使用在模型中定义lazy属性来加载,同options加载方式一致。

模型1,默认

from sqlalchemy.orm import relationship
from db.db_base import BaseModel
from sqlalchemy import Column, String, Boolean, Integer, ForeignKey, Textclass VadminIssueCategory(BaseModel):__tablename__ = "vadmin_help_issue_category"__table_args__ = ({'comment': '常见问题类别表'})name = Column(String(50), index=True, nullable=False, comment="类别名称")platform = Column(String(8), index=True, nullable=False, comment="展示平台")is_active = Column(Boolean, default=True, comment="是否可见")issues = relationship("VadminIssue", back_populates='category')user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id)class VadminIssue(BaseModel):__tablename__ = "vadmin_help_issue"__table_args__ = ({'comment': '常见问题记录表'})category_id = Column(ForeignKey("vadmin_help_issue_category.id", ondelete='CASCADE'), comment="类别")category = relationship("VadminIssueCategory", foreign_keys=category_id, back_populates='issues')title = Column(String(255), index=True, nullable=False, comment="标题")content = Column(Text, comment="内容")view_number = Column(Integer, default=0, comment="查看次数")is_active = Column(Boolean, default=True, comment="是否可见")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id)

查询

class IssueCategoryDal(DalBase):def __init__(self, db: AsyncSession):super(IssueCategoryDal, self).__init__(db, models.VadminIssueCategory, schemas.IssueCategorySimpleOut)async def test(self):"""测试关系"""sql = select(self.model)print(sql)queryset = await self.db.execute(sql)datas = queryset.scalars().all()for data in datas:print(data)print(data.issues)

使用外键报错

模型2,subquery

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Creaet Time    : 2022/7/7 13:41
# @File           : issue.py
# @IDE            : PyCharm
# @desc           : 常见问题from sqlalchemy.orm import relationship
from db.db_base import BaseModel
from sqlalchemy import Column, String, Boolean, Integer, ForeignKey, Textclass VadminIssueCategory(BaseModel):__tablename__ = "vadmin_help_issue_category"__table_args__ = ({'comment': '常见问题类别表'})name = Column(String(50), index=True, nullable=False, comment="类别名称")platform = Column(String(8), index=True, nullable=False, comment="展示平台")is_active = Column(Boolean, default=True, comment="是否可见")issues = relationship("VadminIssue", back_populates='category', lazy="subquery")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id, lazy="subquery")class VadminIssue(BaseModel):__tablename__ = "vadmin_help_issue"__table_args__ = ({'comment': '常见问题记录表'})category_id = Column(ForeignKey("vadmin_help_issue_category.id", ondelete='CASCADE'), comment="类别")category = relationship("VadminIssueCategory", foreign_keys=category_id, back_populates='issues')title = Column(String(255), index=True, nullable=False, comment="标题")content = Column(Text, comment="内容")view_number = Column(Integer, default=0, comment="查看次数")is_active = Column(Boolean, default=True, comment="是否可见")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id)

查询

class IssueCategoryDal(DalBase):def __init__(self, db: AsyncSession):super(IssueCategoryDal, self).__init__(db, models.VadminIssueCategory, schemas.IssueCategorySimpleOut)async def test(self):"""测试关系"""sql = select(self.model)print(sql)queryset = await self.db.execute(sql)datas = queryset.scalars().all()for data in datas:print(data)print(data.user)print(data.issues)

查询结果:

SELECT vadmin_help_issue_category.id, vadmin_help_issue_category.create_datetime, vadmin_help_issue_category.update_datetime, vadmin_help_issue_category.delete_datetime, vadmin_help_issue_category.name, vadmin_help_issue_category.platform, vadmin_help_issue_category.is_active, vadmin_help_issue_category.user_id 
FROM vadmin_help_issue_category
2023-02-17 22:49:31,205 INFO sqlalchemy.engine.Engine SELECT DATABASE()
2023-02-17 22:49:31,205 INFO sqlalchemy.engine.Engine [raw sql] ()
2023-02-17 22:49:31,231 INFO sqlalchemy.engine.Engine SELECT @@sql_mode
2023-02-17 22:49:31,231 INFO sqlalchemy.engine.Engine [raw sql] ()
2023-02-17 22:49:31,244 INFO sqlalchemy.engine.Engine SELECT @@lower_case_table_names
2023-02-17 22:49:31,244 INFO sqlalchemy.engine.Engine [raw sql] ()
2023-02-17 22:49:31,269 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-02-17 22:49:31,270 INFO sqlalchemy.engine.Engine SELECT vadmin_help_issue_category.id, vadmin_help_issue_category.create_datetime, vadmin_help_issue_category.update_datetime, vadmin_help_issue_category.delete_datetime, vadmin_help_issue_category.name, vadmin_help_issue_category.platform, vadmin_help_issue_category.is_active, vadmin_help_issue_category.user_id 
FROM vadmin_help_issue_category
2023-02-17 22:49:31,270 INFO sqlalchemy.engine.Engine [generated in 0.00015s] ()
2023-02-17 22:49:31,287 INFO sqlalchemy.engine.Engine SELECT vadmin_auth_user.id AS vadmin_auth_user_id, vadmin_auth_user.create_datetime AS vadmin_auth_user_create_datetime, vadmin_auth_user.update_datetime AS vadmin_auth_user_update_datetime, vadmin_auth_user.delete_datetime AS vadmin_auth_user_delete_datetime, vadmin_auth_user.avatar AS vadmin_auth_user_avatar, vadmin_auth_user.telephone AS vadmin_auth_user_telephone, vadmin_auth_user.name AS vadmin_auth_user_name, vadmin_auth_user.nickname AS vadmin_auth_user_nickname, vadmin_auth_user.password AS vadmin_auth_user_password, vadmin_auth_user.gender AS vadmin_auth_user_gender, vadmin_auth_user.is_active AS vadmin_auth_user_is_active, vadmin_auth_user.is_cancel AS vadmin_auth_user_is_cancel, vadmin_auth_user.is_reset_password AS vadmin_auth_user_is_reset_password, vadmin_auth_user.last_ip AS vadmin_auth_user_last_ip, vadmin_auth_user.last_login AS vadmin_auth_user_last_login, vadmin_auth_user.is_staff AS vadmin_auth_user_is_staff, vadmin_auth_user.wx_reserve_openid AS vadmin_auth_user_wx_reserve_openid, vadmin_auth_user.is_wx_reserve_openid AS vadmin_auth_user_is_wx_reserve_openid, anon_1.vadmin_help_issue_category_user_id AS anon_1_vadmin_help_issue_category_user_id 
FROM (SELECT DISTINCT vadmin_help_issue_category.user_id AS vadmin_help_issue_category_user_id 
FROM vadmin_help_issue_category) AS anon_1 INNER JOIN vadmin_auth_user ON vadmin_auth_user.id = anon_1.vadmin_help_issue_category_user_id
2023-02-17 22:49:31,287 INFO sqlalchemy.engine.Engine [generated in 0.00017s] ()
2023-02-17 22:49:31,302 INFO sqlalchemy.engine.Engine SELECT vadmin_help_issue.id AS vadmin_help_issue_id, vadmin_help_issue.create_datetime AS vadmin_help_issue_create_datetime, vadmin_help_issue.update_datetime AS vadmin_help_issue_update_datetime, vadmin_help_issue.delete_datetime AS vadmin_help_issue_delete_datetime, vadmin_help_issue.category_id AS vadmin_help_issue_category_id, vadmin_help_issue.title AS vadmin_help_issue_title, vadmin_help_issue.content AS vadmin_help_issue_content, vadmin_help_issue.view_number AS vadmin_help_issue_view_number, vadmin_help_issue.is_active AS vadmin_help_issue_is_active, vadmin_help_issue.user_id AS vadmin_help_issue_user_id, anon_1.vadmin_help_issue_category_id AS anon_1_vadmin_help_issue_category_id 
FROM (SELECT vadmin_help_issue_category.id AS vadmin_help_issue_category_id 
FROM vadmin_help_issue_category) AS anon_1 INNER JOIN vadmin_help_issue ON anon_1.vadmin_help_issue_category_id = vadmin_help_issue.category_id
2023-02-17 22:49:31,302 INFO sqlalchemy.engine.Engine [generated in 0.00015s] ()
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000021DECA08E50>
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000021DECA09C90>
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000021DECA09E40>
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000021DECA0A650>
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000021DECA430D0>
INFO:     127.0.0.1:57513 - "GET /vadmin/help/issue/categorys/platform/2/ HTTP/1.1" 200 OK
2023-02-17 22:49:31,318 INFO sqlalchemy.engine.Engine COMMIT

是否触发外键,执行时都会去先加载出来

通过内连接查询

模型3,selectin

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Creaet Time    : 2022/7/7 13:41
# @File           : issue.py
# @IDE            : PyCharm
# @desc           : 常见问题from sqlalchemy.orm import relationship
from db.db_base import BaseModel
from sqlalchemy import Column, String, Boolean, Integer, ForeignKey, Textclass VadminIssueCategory(BaseModel):__tablename__ = "vadmin_help_issue_category"__table_args__ = ({'comment': '常见问题类别表'})name = Column(String(50), index=True, nullable=False, comment="类别名称")platform = Column(String(8), index=True, nullable=False, comment="展示平台")is_active = Column(Boolean, default=True, comment="是否可见")issues = relationship("VadminIssue", back_populates='category', lazy="selectin")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id, lazy="selectin")class VadminIssue(BaseModel):__tablename__ = "vadmin_help_issue"__table_args__ = ({'comment': '常见问题记录表'})category_id = Column(ForeignKey("vadmin_help_issue_category.id", ondelete='CASCADE'), comment="类别")category = relationship("VadminIssueCategory", foreign_keys=category_id, back_populates='issues')title = Column(String(255), index=True, nullable=False, comment="标题")content = Column(Text, comment="内容")view_number = Column(Integer, default=0, comment="查看次数")is_active = Column(Boolean, default=True, comment="是否可见")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id)

查询

class IssueCategoryDal(DalBase):def __init__(self, db: AsyncSession):super(IssueCategoryDal, self).__init__(db, models.VadminIssueCategory, schemas.IssueCategorySimpleOut)async def test(self):"""测试关系"""sql = select(self.model)print(sql)queryset = await self.db.execute(sql)datas = queryset.scalars().all()for data in datas:print(data)print(data.user)print(data.issues)

查询结果:

SELECT vadmin_help_issue_category.id, vadmin_help_issue_category.create_datetime, vadmin_help_issue_category.update_datetime, vadmin_help_issue_category.delete_datetime, vadmin_help_issue_category.name, vadmin_help_issue_category.platform, vadmin_help_issue_category.is_active, vadmin_help_issue_category.user_id 
FROM vadmin_help_issue_category
2023-02-17 23:02:57,891 INFO sqlalchemy.engine.Engine SELECT DATABASE()
2023-02-17 23:02:57,891 INFO sqlalchemy.engine.Engine [raw sql] ()
2023-02-17 23:02:57,925 INFO sqlalchemy.engine.Engine SELECT @@sql_mode
2023-02-17 23:02:57,925 INFO sqlalchemy.engine.Engine [raw sql] ()
2023-02-17 23:02:57,942 INFO sqlalchemy.engine.Engine SELECT @@lower_case_table_names
2023-02-17 23:02:57,942 INFO sqlalchemy.engine.Engine [raw sql] ()
2023-02-17 23:02:57,976 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-02-17 23:02:57,977 INFO sqlalchemy.engine.Engine SELECT vadmin_help_issue_category.id, vadmin_help_issue_category.create_datetime, vadmin_help_issue_category.update_datetime, vadmin_help_issue_category.delete_datetime, vadmin_help_issue_category.name, vadmin_help_issue_category.platform, vadmin_help_issue_category.is_active, vadmin_help_issue_category.user_id 
FROM vadmin_help_issue_category
2023-02-17 23:02:57,977 INFO sqlalchemy.engine.Engine [generated in 0.00013s] ()
2023-02-17 23:02:57,995 INFO sqlalchemy.engine.Engine SELECT vadmin_help_issue.category_id AS vadmin_help_issue_category_id, vadmin_help_issue.id AS vadmin_help_issue_id, vadmin_help_issue.create_datetime AS vadmin_help_issue_create_datetime, vadmin_help_issue.update_datetime AS vadmin_help_issue_update_datetime, vadmin_help_issue.delete_datetime AS vadmin_help_issue_delete_datetime, vadmin_help_issue.title AS vadmin_help_issue_title, vadmin_help_issue.content AS vadmin_help_issue_content, vadmin_help_issue.view_number AS vadmin_help_issue_view_number, vadmin_help_issue.is_active AS vadmin_help_issue_is_active, vadmin_help_issue.user_id AS vadmin_help_issue_user_id 
FROM vadmin_help_issue 
WHERE vadmin_help_issue.category_id IN (%s, %s, %s, %s, %s)
2023-02-17 23:02:57,996 INFO sqlalchemy.engine.Engine [generated in 0.00019s] (1, 2, 3, 4, 5)
2023-02-17 23:02:58,015 INFO sqlalchemy.engine.Engine SELECT vadmin_auth_user.id AS vadmin_auth_user_id, vadmin_auth_user.create_datetime AS vadmin_auth_user_create_datetime, vadmin_auth_user.update_datetime AS vadmin_auth_user_update_datetime, vadmin_auth_user.delete_datetime AS vadmin_auth_user_delete_datetime, vadmin_auth_user.avatar AS vadmin_auth_user_avatar, vadmin_auth_user.telephone AS vadmin_auth_user_telephone, vadmin_auth_user.name AS vadmin_auth_user_name, vadmin_auth_user.nickname AS vadmin_auth_user_nickname, vadmin_auth_user.password AS vadmin_auth_user_password, vadmin_auth_user.gender AS vadmin_auth_user_gender, vadmin_auth_user.is_active AS vadmin_auth_user_is_active, vadmin_auth_user.is_cancel AS vadmin_auth_user_is_cancel, vadmin_auth_user.is_reset_password AS vadmin_auth_user_is_reset_password, vadmin_auth_user.last_ip AS vadmin_auth_user_last_ip, vadmin_auth_user.last_login AS vadmin_auth_user_last_login, vadmin_auth_user.is_staff AS vadmin_auth_user_is_staff, vadmin_auth_user.wx_reserve_openid AS vadmin_auth_user_wx_reserve_openid, vadmin_auth_user.is_wx_reserve_openid AS vadmin_auth_user_is_wx_reserve_openid 
FROM vadmin_auth_user 
WHERE vadmin_auth_user.id IN (%s)
2023-02-17 23:02:58,015 INFO sqlalchemy.engine.Engine [generated in 0.00019s] (1,)
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000025359A6DA80>
<apps.vadmin.auth.models.user.VadminUser object at 0x0000025359A8EF80>
[<apps.vadmin.help.models.issue.VadminIssue object at 0x0000025359A8C490>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000025359A8C580>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000025359A8C5B0>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000025359A8C940>]
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000025359A6DAE0>
<apps.vadmin.auth.models.user.VadminUser object at 0x0000025359A8EF80>
[]
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000025359A6DB40>
<apps.vadmin.auth.models.user.VadminUser object at 0x0000025359A8EF80>
[]
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000025359A6DBA0>
<apps.vadmin.auth.models.user.VadminUser object at 0x0000025359A8EF80>
[<apps.vadmin.help.models.issue.VadminIssue object at 0x0000025359A8C640>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000025359A8C700>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000025359A8C7C0>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000025359A8C880>]
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000025359A6DC00>
<apps.vadmin.auth.models.user.VadminUser object at 0x0000025359A8EF80>
[<apps.vadmin.help.models.issue.VadminIssue object at 0x0000025359A8CA00>]
INFO:     127.0.0.1:64399 - "GET /vadmin/help/issue/categorys/platform/2/ HTTP/1.1" 200 OK
2023-02-17 23:02:58,034 INFO sqlalchemy.engine.Engine COMMIT

是否触发外键,执行时都会去先加载出来,只是和subquery查询的方式不一样,这个是查询的关联表

模型4,joined

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Creaet Time    : 2022/7/7 13:41
# @File           : issue.py
# @IDE            : PyCharm
# @desc           : 常见问题from sqlalchemy.orm import relationship
from db.db_base import BaseModel
from sqlalchemy import Column, String, Boolean, Integer, ForeignKey, Textclass VadminIssueCategory(BaseModel):__tablename__ = "vadmin_help_issue_category"__table_args__ = ({'comment': '常见问题类别表'})name = Column(String(50), index=True, nullable=False, comment="类别名称")platform = Column(String(8), index=True, nullable=False, comment="展示平台")is_active = Column(Boolean, default=True, comment="是否可见")issues = relationship("VadminIssue", back_populates='category', lazy="joined")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id, lazy="joined")class VadminIssue(BaseModel):__tablename__ = "vadmin_help_issue"__table_args__ = ({'comment': '常见问题记录表'})category_id = Column(ForeignKey("vadmin_help_issue_category.id", ondelete='CASCADE'), comment="类别")category = relationship("VadminIssueCategory", foreign_keys=category_id, back_populates='issues')title = Column(String(255), index=True, nullable=False, comment="标题")content = Column(Text, comment="内容")view_number = Column(Integer, default=0, comment="查看次数")is_active = Column(Boolean, default=True, comment="是否可见")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id)

查询

class IssueCategoryDal(DalBase):def __init__(self, db: AsyncSession):super(IssueCategoryDal, self).__init__(db, models.VadminIssueCategory, schemas.IssueCategorySimpleOut)async def test(self):"""测试关系"""sql = select(self.model)print(sql)queryset = await self.db.execute(sql)datas = queryset.scalars().all()for data in datas:print(data)print(data.user)print(data.issues)

查询结果,一条SQL查询

SELECTvadmin_help_issue_category.id,vadmin_help_issue_category.create_datetime,vadmin_help_issue_category.update_datetime,vadmin_help_issue_category.delete_datetime,vadmin_help_issue_category.NAME,vadmin_help_issue_category.platform,vadmin_help_issue_category.is_active,vadmin_help_issue_category.user_id,vadmin_help_issue_1.id AS id_1,vadmin_help_issue_1.create_datetime AS create_datetime_1,vadmin_help_issue_1.update_datetime AS update_datetime_1,vadmin_help_issue_1.delete_datetime AS delete_datetime_1,vadmin_help_issue_1.category_id,vadmin_help_issue_1.title,vadmin_help_issue_1.content,vadmin_help_issue_1.view_number,vadmin_help_issue_1.is_active AS is_active_1,vadmin_help_issue_1.user_id AS user_id_1,vadmin_auth_user_1.id AS id_2,vadmin_auth_user_1.create_datetime AS create_datetime_2,vadmin_auth_user_1.update_datetime AS update_datetime_2,vadmin_auth_user_1.delete_datetime AS delete_datetime_2,vadmin_auth_user_1.avatar,vadmin_auth_user_1.telephone,vadmin_auth_user_1.NAME AS name_1,vadmin_auth_user_1.nickname,vadmin_auth_user_1.PASSWORD,vadmin_auth_user_1.gender,vadmin_auth_user_1.is_active AS is_active_2,vadmin_auth_user_1.is_cancel,vadmin_auth_user_1.is_reset_password,vadmin_auth_user_1.last_ip,vadmin_auth_user_1.last_login,vadmin_auth_user_1.is_staff,vadmin_auth_user_1.wx_reserve_openid,vadmin_auth_user_1.is_wx_reserve_openid 
FROMvadmin_help_issue_categoryLEFT OUTER JOIN vadmin_help_issue AS vadmin_help_issue_1 ON vadmin_help_issue_category.id = vadmin_help_issue_1.category_idLEFT OUTER JOIN vadmin_auth_user AS vadmin_auth_user_1 ON vadmin_auth_user_1.id = vadmin_help_issue_category.user_id

是否触发外键,执行时都会去先加载出来

查询方式使用左连接查询

模型5,select

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Creaet Time    : 2022/7/7 13:41
# @File           : issue.py
# @IDE            : PyCharm
# @desc           : 常见问题from sqlalchemy.orm import relationship
from db.db_base import BaseModel
from sqlalchemy import Column, String, Boolean, Integer, ForeignKey, Textclass VadminIssueCategory(BaseModel):__tablename__ = "vadmin_help_issue_category"__table_args__ = ({'comment': '常见问题类别表'})name = Column(String(50), index=True, nullable=False, comment="类别名称")platform = Column(String(8), index=True, nullable=False, comment="展示平台")is_active = Column(Boolean, default=True, comment="是否可见")issues = relationship("VadminIssue", back_populates='category', lazy="select")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id, lazy="select")class VadminIssue(BaseModel):__tablename__ = "vadmin_help_issue"__table_args__ = ({'comment': '常见问题记录表'})category_id = Column(ForeignKey("vadmin_help_issue_category.id", ondelete='CASCADE'), comment="类别")category = relationship("VadminIssueCategory", foreign_keys=category_id, back_populates='issues')title = Column(String(255), index=True, nullable=False, comment="标题")content = Column(Text, comment="内容")view_number = Column(Integer, default=0, comment="查看次数")is_active = Column(Boolean, default=True, comment="是否可见")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id)

查询

class IssueCategoryDal(DalBase):def __init__(self, db: AsyncSession):super(IssueCategoryDal, self).__init__(db, models.VadminIssueCategory, schemas.IssueCategorySimpleOut)async def test(self):"""测试关系"""sql = select(self.model)print(sql)queryset = await self.db.execute(sql)datas = queryset.scalars().all()for data in datas:print(data)print(data.user)print(data.issues)

使用外键报错

模型6,immediate

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Creaet Time    : 2022/7/7 13:41
# @File           : issue.py
# @IDE            : PyCharm
# @desc           : 常见问题from sqlalchemy.orm import relationship
from db.db_base import BaseModel
from sqlalchemy import Column, String, Boolean, Integer, ForeignKey, Textclass VadminIssueCategory(BaseModel):__tablename__ = "vadmin_help_issue_category"__table_args__ = ({'comment': '常见问题类别表'})name = Column(String(50), index=True, nullable=False, comment="类别名称")platform = Column(String(8), index=True, nullable=False, comment="展示平台")is_active = Column(Boolean, default=True, comment="是否可见")issues = relationship("VadminIssue", back_populates='category', lazy="immediate")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id, lazy="immediate")class VadminIssue(BaseModel):__tablename__ = "vadmin_help_issue"__table_args__ = ({'comment': '常见问题记录表'})category_id = Column(ForeignKey("vadmin_help_issue_category.id", ondelete='CASCADE'), comment="类别")category = relationship("VadminIssueCategory", foreign_keys=category_id, back_populates='issues')title = Column(String(255), index=True, nullable=False, comment="标题")content = Column(Text, comment="内容")view_number = Column(Integer, default=0, comment="查看次数")is_active = Column(Boolean, default=True, comment="是否可见")user_id = Column(ForeignKey("vadmin_auth_user.id", ondelete='CASCADE'), comment="创建人")user = relationship("VadminUser", foreign_keys=user_id)

查询

class IssueCategoryDal(DalBase):def __init__(self, db: AsyncSession):super(IssueCategoryDal, self).__init__(db, models.VadminIssueCategory, schemas.IssueCategorySimpleOut)async def test(self):"""测试关系"""sql = select(self.model)print(sql)queryset = await self.db.execute(sql)datas = queryset.scalars().all()for data in datas:print(data)print(data.user)print(data.issues)

查询结果

SELECT vadmin_help_issue_category.id, vadmin_help_issue_category.create_datetime, vadmin_help_issue_category.update_datetime, vadmin_help_issue_category.delete_datetime, vadmin_help_issue_category.name, vadmin_help_issue_category.platform, vadmin_help_issue_category.is_active, vadmin_help_issue_category.user_id 
FROM vadmin_help_issue_category
2023-02-17 23:26:18,696 INFO sqlalchemy.engine.Engine SELECT DATABASE()
2023-02-17 23:26:18,696 INFO sqlalchemy.engine.Engine [raw sql] ()
2023-02-17 23:26:18,722 INFO sqlalchemy.engine.Engine SELECT @@sql_mode
2023-02-17 23:26:18,722 INFO sqlalchemy.engine.Engine [raw sql] ()
2023-02-17 23:26:18,735 INFO sqlalchemy.engine.Engine SELECT @@lower_case_table_names
2023-02-17 23:26:18,735 INFO sqlalchemy.engine.Engine [raw sql] ()
2023-02-17 23:26:18,760 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-02-17 23:26:18,761 INFO sqlalchemy.engine.Engine SELECT vadmin_help_issue_category.id, vadmin_help_issue_category.create_datetime, vadmin_help_issue_category.update_datetime, vadmin_help_issue_category.delete_datetime, vadmin_help_issue_category.name, vadmin_help_issue_category.platform, vadmin_help_issue_category.is_active, vadmin_help_issue_category.user_id 
FROM vadmin_help_issue_category
2023-02-17 23:26:18,761 INFO sqlalchemy.engine.Engine [generated in 0.00015s] ()
2023-02-17 23:26:18,776 INFO sqlalchemy.engine.Engine SELECT vadmin_help_issue.id AS vadmin_help_issue_id, vadmin_help_issue.create_datetime AS vadmin_help_issue_create_datetime, vadmin_help_issue.update_datetime AS vadmin_help_issue_update_datetime, vadmin_help_issue.delete_datetime AS vadmin_help_issue_delete_datetime, vadmin_help_issue.category_id AS vadmin_help_issue_category_id, vadmin_help_issue.title AS vadmin_help_issue_title, vadmin_help_issue.content AS vadmin_help_issue_content, vadmin_help_issue.view_number AS vadmin_help_issue_view_number, vadmin_help_issue.is_active AS vadmin_help_issue_is_active, vadmin_help_issue.user_id AS vadmin_help_issue_user_id 
FROM vadmin_help_issue 
WHERE %s = vadmin_help_issue.category_id
2023-02-17 23:26:18,776 INFO sqlalchemy.engine.Engine [generated in 0.00017s] (1,)
2023-02-17 23:26:18,792 INFO sqlalchemy.engine.Engine SELECT vadmin_auth_user.id AS vadmin_auth_user_id, vadmin_auth_user.create_datetime AS vadmin_auth_user_create_datetime, vadmin_auth_user.update_datetime AS vadmin_auth_user_update_datetime, vadmin_auth_user.delete_datetime AS vadmin_auth_user_delete_datetime, vadmin_auth_user.avatar AS vadmin_auth_user_avatar, vadmin_auth_user.telephone AS vadmin_auth_user_telephone, vadmin_auth_user.name AS vadmin_auth_user_name, vadmin_auth_user.nickname AS vadmin_auth_user_nickname, vadmin_auth_user.password AS vadmin_auth_user_password, vadmin_auth_user.gender AS vadmin_auth_user_gender, vadmin_auth_user.is_active AS vadmin_auth_user_is_active, vadmin_auth_user.is_cancel AS vadmin_auth_user_is_cancel, vadmin_auth_user.is_reset_password AS vadmin_auth_user_is_reset_password, vadmin_auth_user.last_ip AS vadmin_auth_user_last_ip, vadmin_auth_user.last_login AS vadmin_auth_user_last_login, vadmin_auth_user.is_staff AS vadmin_auth_user_is_staff, vadmin_auth_user.wx_reserve_openid AS vadmin_auth_user_wx_reserve_openid, vadmin_auth_user.is_wx_reserve_openid AS vadmin_auth_user_is_wx_reserve_openid 
FROM vadmin_auth_user 
WHERE vadmin_auth_user.id = %s
2023-02-17 23:26:18,792 INFO sqlalchemy.engine.Engine [generated in 0.00020s] (1,)
2023-02-17 23:26:18,806 INFO sqlalchemy.engine.Engine SELECT vadmin_help_issue.id AS vadmin_help_issue_id, vadmin_help_issue.create_datetime AS vadmin_help_issue_create_datetime, vadmin_help_issue.update_datetime AS vadmin_help_issue_update_datetime, vadmin_help_issue.delete_datetime AS vadmin_help_issue_delete_datetime, vadmin_help_issue.category_id AS vadmin_help_issue_category_id, vadmin_help_issue.title AS vadmin_help_issue_title, vadmin_help_issue.content AS vadmin_help_issue_content, vadmin_help_issue.view_number AS vadmin_help_issue_view_number, vadmin_help_issue.is_active AS vadmin_help_issue_is_active, vadmin_help_issue.user_id AS vadmin_help_issue_user_id 
FROM vadmin_help_issue 
WHERE %s = vadmin_help_issue.category_id
2023-02-17 23:26:18,806 INFO sqlalchemy.engine.Engine [cached since 0.03102s ago] (2,)
2023-02-17 23:26:18,820 INFO sqlalchemy.engine.Engine SELECT vadmin_help_issue.id AS vadmin_help_issue_id, vadmin_help_issue.create_datetime AS vadmin_help_issue_create_datetime, vadmin_help_issue.update_datetime AS vadmin_help_issue_update_datetime, vadmin_help_issue.delete_datetime AS vadmin_help_issue_delete_datetime, vadmin_help_issue.category_id AS vadmin_help_issue_category_id, vadmin_help_issue.title AS vadmin_help_issue_title, vadmin_help_issue.content AS vadmin_help_issue_content, vadmin_help_issue.view_number AS vadmin_help_issue_view_number, vadmin_help_issue.is_active AS vadmin_help_issue_is_active, vadmin_help_issue.user_id AS vadmin_help_issue_user_id 
FROM vadmin_help_issue 
WHERE %s = vadmin_help_issue.category_id
2023-02-17 23:26:18,821 INFO sqlalchemy.engine.Engine [cached since 0.04498s ago] (3,)
2023-02-17 23:26:18,834 INFO sqlalchemy.engine.Engine SELECT vadmin_help_issue.id AS vadmin_help_issue_id, vadmin_help_issue.create_datetime AS vadmin_help_issue_create_datetime, vadmin_help_issue.update_datetime AS vadmin_help_issue_update_datetime, vadmin_help_issue.delete_datetime AS vadmin_help_issue_delete_datetime, vadmin_help_issue.category_id AS vadmin_help_issue_category_id, vadmin_help_issue.title AS vadmin_help_issue_title, vadmin_help_issue.content AS vadmin_help_issue_content, vadmin_help_issue.view_number AS vadmin_help_issue_view_number, vadmin_help_issue.is_active AS vadmin_help_issue_is_active, vadmin_help_issue.user_id AS vadmin_help_issue_user_id 
FROM vadmin_help_issue 
WHERE %s = vadmin_help_issue.category_id
2023-02-17 23:26:18,834 INFO sqlalchemy.engine.Engine [cached since 0.05871s ago] (4,)
2023-02-17 23:26:18,848 INFO sqlalchemy.engine.Engine SELECT vadmin_help_issue.id AS vadmin_help_issue_id, vadmin_help_issue.create_datetime AS vadmin_help_issue_create_datetime, vadmin_help_issue.update_datetime AS vadmin_help_issue_update_datetime, vadmin_help_issue.delete_datetime AS vadmin_help_issue_delete_datetime, vadmin_help_issue.category_id AS vadmin_help_issue_category_id, vadmin_help_issue.title AS vadmin_help_issue_title, vadmin_help_issue.content AS vadmin_help_issue_content, vadmin_help_issue.view_number AS vadmin_help_issue_view_number, vadmin_help_issue.is_active AS vadmin_help_issue_is_active, vadmin_help_issue.user_id AS vadmin_help_issue_user_id 
FROM vadmin_help_issue 
WHERE %s = vadmin_help_issue.category_id
2023-02-17 23:26:18,848 INFO sqlalchemy.engine.Engine [cached since 0.07242s ago] (5,)
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000020AB36E8DC0>
<apps.vadmin.auth.models.user.VadminUser object at 0x0000020AB36EA620>
[<apps.vadmin.help.models.issue.VadminIssue object at 0x0000020AB36EBB50>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000020AB36EBAC0>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000020AB36EBBE0>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000020AB36EBC40>]
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000020AB36BD000>
<apps.vadmin.auth.models.user.VadminUser object at 0x0000020AB36EA620>
[]
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000020AB36E9C60>
<apps.vadmin.auth.models.user.VadminUser object at 0x0000020AB36EA620>
[]
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000020AB36EA8F0>
<apps.vadmin.auth.models.user.VadminUser object at 0x0000020AB36EA620>
[<apps.vadmin.help.models.issue.VadminIssue object at 0x0000020AB370E6E0>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000020AB370E650>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000020AB370E770>, <apps.vadmin.help.models.issue.VadminIssue object at 0x0000020AB370E7D0>]
<apps.vadmin.help.models.issue.VadminIssueCategory object at 0x0000020AB36EA1D0>
<apps.vadmin.auth.models.user.VadminUser object at 0x0000020AB36EA620>
[<apps.vadmin.help.models.issue.VadminIssue object at 0x0000020AB370EA10>]
INFO:     127.0.0.1:56143 - "GET /vadmin/help/issue/categorys/platform/2/ HTTP/1.1" 200 OK
2023-02-17 23:26:18,864 INFO sqlalchemy.engine.Engine COMMIT

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/50083.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

好用的码字软件,年入百万的大神作家们都在用

如今&#xff0c;码字软件需求很大&#xff0c;市面上也出现了很多码字软件&#xff0c;但找到一款适合自己的码字软件却并不容易&#xff0c;那么你知道大些大神作家们喜欢用什么软件么&#xff1f;其实我也不知道&#xff0c;但是我发现了一个秘密&#xff0c;那就是由橙瓜打…

猿创征文|五款程序员必备神级工具,看看你用过几个?

程序员必备的神级工具 一、有道词典二、XMind三、Notepad四、Typora五、Everything 一、有道词典 邻居家有个小孩&#xff0c;一个资深学瘾少年&#xff0c;有他经过的地方&#xff0c;总会引起周边妇女赞扬&#xff08;以及对其余所有孩子的无限嘲讽&#xff09;。 有一次&am…

一篇万字博文带你入坑爬虫这条不归路 【万字图文】

&#x1f47b;最近&#xff0c;很多粉丝私信我问——爬虫到底是什么&#xff1f;学习爬虫到底该从何下手&#xff1f;&#x1f47b; &#x1f62c;其实&#xff0c;我想说的也是曾经的我身为小白的时候某些大牛对我说过的——很多时候我们都有一颗想要学习新知识的心&#xff…

微软/Hotmail验证码识别97%识别率方案

如图所示&#xff0c;微软Hotmail的验证码与我们往常所见的验证码略有不同&#xff0c;他是 【双层粘结】 的验证码&#xff0c;这对于我们识别有什么影响呢&#xff1f; 我们先来看CTC算法的TimeStep在语音识别中的表示&#xff1a; 因为位数不固定&#xff0c;一般通过端到…

EasyCaptcha图形验证码工具

介绍 Java图形验证码工具&#xff0c;支持gif&#xff08;动图&#xff09;、中文、算术等类型&#xff0c;可用于Java Web、JavaSE等项目。 快速开始 导入依赖 <dependency><groupId>com.github.whvcse</groupId><artifactId>easy-captcha</art…

您的captcha验证码设置对了吗?

Web App 评估可能是当今最流行的渗透测试之一。它们非常受欢迎&#xff0c;以至于 Hacker One 和 Bug Crowd 等公共漏洞赏金网站为希望修复 XSS、SQL 注入、CSRF 等漏洞的公司提供了数百个程序。许多公司还拥有自己的赏金计划&#xff0c;用于向以下人员报告 Web 漏洞一个安全团…

微软验证码项目 Captcha Code Demo 从 .NET Core 1.1.2升级到2.1.0

How to make and use captcha code in ASP.NET Core 在ASP.NET Core 中如何实现 captcha 验证码 这个 Demo 是在微软 msdn 中找到的&#xff0c;早期 2017年6月30日发布。发现它的时候是 2019年10月30日。这时候 .NET Core 版本 3.0 已发布。Visual Studio 2019 也已经自动更新…

【文心一言】广告文案、演讲稿与请假条自动生成

前言 作为一名大学生而言&#xff0c;平时参加或者举办一些学校组织的活动的时候&#xff0c;总是避免不了需要准备一些演讲稿、广告宣传文案等内容&#xff0c;甚至于在疫情十分严重的这几年内&#xff0c;如何跟老师“委婉的”请假&#xff0c;也成为了我日常头疼的事情。但在…

如何设计好一条推送通知

你注意过么&#xff0c;每天从不同的 App 上收到的大量的推送通知与提醒&#xff0c;这些通知里有多少你真的有兴趣? 智能手表屏幕上无意义的通知 每天&#xff0c;用户对各种没用的通知应接不暇&#xff0c;这些通知让他们分散注意力&#xff0c;甚至成为了骚扰。骚扰的通知…

通知栏消息文案写作干货:个推手把手教你写

去搜一搜消息推送的入门秘籍、干货精华&#xff0c;始终绕不开“推送有价值的信息很关键”&#xff0c;其载体则是走心的文案&#xff0c;那么对于APP运营人员来说&#xff0c;什么样的推送文案称得上“优秀”&#xff1f;本文结合部分APP的通知栏消息案例&#xff0c;从中规中…

通告,消息,提醒,设计

通告Bulletin&#xff1a; 平台发&#xff0c;用户收。分为实时通告和非实时通告。通告有优先级&#xff1a;紧急&#xff0c;高&#xff0c;普通。 平台向单个用户发&#xff0c;平台向多个用户发&#xff0c;平台向某一个用户类型发&#xff0c;平台向全部用户发。 平台发布通…

Twitter注册如何做到ip防关联

因为Twitter还可以用来做广告&#xff0c;所以很多跨境电商都是通过Twitter来工作的。对于这些用户来说&#xff0c;一个Twitter账号肯定是不够的&#xff1b;多个账户需要同时操作。但是&#xff0c;如果你使用相同的浏览器或相同的ip地址&#xff0c;你很快就会决定询问关联的…

IP-GUARD控制台账户输入多次错误密码锁定后该如何解锁?

其他管理员账户给锁定了,暂时只能等其锁定时间到了才可以再次输入,默认是设置是锁定30min; 1、如果急需此账户查看,可以使用admin系统管理员账户登录控制台,在工具-账户中清除这个账户的密码,重新登录设置密码。

Oracle用户被锁查哪个具体IP地址造成的

Oracle用户被锁查哪个具体IP地址造成的 1、用dba角色的用户登陆&#xff0c;进行解锁&#xff0c;先设置具体时间格式&#xff0c;以便查看具体时间 SQL> alter session set nls_date_format‘yyyy-mm-dd hh24:mi:ss’; Session altered. 2、查看具体的被锁时间 SQL>…

在 Linux 下利用ipset大量屏蔽恶意 IP 地址

很多情况下&#xff0c;你可能需要在Linux下屏蔽IP地址。比如&#xff0c;作为一个终端用户&#xff0c;你可能想要免受间谍软件或者IP追踪的困扰。或者当你在运行P2P软件时。你可能想要过滤反P2P活动的网络链接。如果你是一名系统管理员&#xff0c;你可能想要禁止垃圾IP地址访…

EasyCharts,简单易用的Excel图表插件

EasyCharts是一款简单易用的Excel插件&#xff0c;主要有一键生成Excel未提供的图表、图表美化、配色参考等功能&#xff0c;轻轻松松就能搞定需要通过编程或者复杂操作才能实现的图表啦&#xff01; 以下展示插件中的部分图表类型。

分享一款好用的图表制作软件,简单、美观又高效!

换新工作后&#xff0c;老板给我一个任务&#xff0c;让我每周制作数据报告&#xff0c;辛苦做了半天&#xff0c;谁知道老板是一个“颜值即正义"人&#xff0c;嫌弃我的图表不好看&#xff0c;好惆怅。然后一个同行的好朋友给我分享了一款好用的图表制作软件—BDP&#x…

2021-07-19 .NET高级班 113-AmCharts实时图表的使用

@{ViewData["Title"] = "Index"; }<div class="row"><div class="col-lg-3 col-md-3 col-sm-6 col-xs-12"><div class="dashboard-stat blue">

一款简单、实时、酷炫的图表制作软件

当今&#xff0c;图表制作已经成了每一个职场人的日常&#xff0c;如果列个职场基本傍身技能排行榜&#xff0c;图表制作怕是前三了。虽说它是工作日常&#xff0c;虽说它很重要&#xff0c;但很多人还是做不好图表。 比如&#xff0c;我们想象中的图表可能是这样的&#xff1a…

动态数据可视化图表制作,我只用这款软件

相信很多数据人都会困扰一个问题就是&#xff0c;同为数据分析师&#xff0c;为什么我做的动态数据可视化图表又费时又费力还看起来不咋地&#xff0c;而别人做动图就是轻轻松松还高大上&#xff1f; 在这里&#xff0c;小编分享几个优秀动态数据可视化图表需要具备的几个要素…