flask_sqlalchemy relationship 子表排序

背景:

使用flask_sqlalchemy 的orm 时总不可避免的遇到子表排序问题

材料:

省略

制作:

直接看下面2段代码片段(一对多关系组合),自行理解:

1、多的一方实体

from .exts import db
from flask_login import UserMixin
from datetime import datetime


class SchedulerLog(db.Model, UserMixin):
    __tablename__ = 'scheduler_log'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    created_at = db.Column(db.TIMESTAMP, default=datetime.utcnow)
    task_id = db.Column(db.Integer, db.ForeignKey('scheduler_task.id'))
    execute_type = db.Column(db.Integer)
    description = db.Column(db.String(228))
    result_status = db.Column(db.Integer)
    task_info = db.Column(db.String(228))
    org_code = db.Column(db.String(228))

2、少的一方实体

from .exts import db
from flask_login import UserMixin
from datetime import datetime


class SchedulerTask(db.Model, UserMixin):
    __tablename__ = 'scheduler_task'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    created_at = db.Column(db.TIMESTAMP, default=datetime.utcnow)
    updated_at = db.Column(db.TIMESTAMP, default=datetime.utcnow)
    description = db.Column(db.String(228))
    task_name = db.Column(db.String(228))
    task_code = db.Column(db.String(228))
    status = db.Column(db.Integer)
    exe_status = db.Column(db.Integer)
    job_id = db.Column(db.Integer())
    task_type = db.Column(db.Integer())
    org_code = db.Column(db.String(228))
    tasklogs = db.relationship('SchedulerLog', backref='scheduler_task', order_by='SchedulerLog.id.desc()', lazy='dynamic')

3、relationship 关系函数下自带order_by排序方法,直接按照实体进行映射,但要记住 desc()/asc() 后面一定要有(),否则会报错(本人被坑了2个小时) ,order_by的源码如下:

def relationship(
    argument: Optional[_RelationshipArgumentType[Any]] = None,
    secondary: Optional[_RelationshipSecondaryArgument] = None,
    *,
    uselist: Optional[bool] = None,
    collection_class: Optional[
        Union[Type[Collection[Any]], Callable[[], Collection[Any]]]
    ] = None,
    primaryjoin: Optional[_RelationshipJoinConditionArgument] = None,
    secondaryjoin: Optional[_RelationshipJoinConditionArgument] = None,
    back_populates: Optional[str] = None,
    order_by: _ORMOrderByArgument = False,
    backref: Optional[ORMBackrefArgument] = None,
    overlaps: Optional[str] = None,
    post_update: bool = False,
    cascade: str = "save-update, merge",
    viewonly: bool = False,
    init: Union[_NoArg, bool] = _NoArg.NO_ARG,
    repr: Union[_NoArg, bool] = _NoArg.NO_ARG,  # noqa: A002
    default: Union[_NoArg, _T] = _NoArg.NO_ARG,
    default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
    compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
    kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
    hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG,  # noqa: A002
    lazy: _LazyLoadArgumentType = "select",
    passive_deletes: Union[Literal["all"], bool] = False,
    passive_updates: bool = True,
    active_history: bool = False,
    enable_typechecks: bool = True,
    foreign_keys: Optional[_ORMColCollectionArgument] = None,
    remote_side: Optional[_ORMColCollectionArgument] = None,
    join_depth: Optional[int] = None,
    comparator_factory: Optional[
        Type[RelationshipProperty.Comparator[Any]]
    ] = None,
    single_parent: bool = False,
    innerjoin: bool = False,
    distinct_target_key: Optional[bool] = None,
    load_on_pending: bool = False,
    query_class: Optional[Type[Query[Any]]] = None,
    info: Optional[_InfoType] = None,
    omit_join: Literal[None, False] = None,
    sync_backref: Optional[bool] = None,
    **kw: Any,
相关推荐
线上放牧人4 分钟前
Go语言编译的exe文件占用内存过大解决办法
开发语言·后端·golang
m0_dawn9 分钟前
(蓝桥杯)二维数组前缀和典型例题——子矩阵求和
python·学习·算法·职场和发展·蓝桥杯
续写少年!29 分钟前
空指针:HttpSession异常,SpringBoot集成WebSocket
spring boot·后端·websocket
三天不学习1 小时前
【Delete 删除数据语法合集】.NET开源ORM框架 SqlSugar 系列
后端·开源·.net·orm·微软技术·sqlsugar
蹦蹦跳跳真可爱5891 小时前
Python----Python基础(字符串,列表,元组,字典,集合的总结)
开发语言·python
Ma_si1 小时前
Python脚本自动发送电子邮件
python
元_汐2 小时前
【Python通过UDP协议传输视频数据】(界面识别)
开发语言·网络·python·网络协议·tcp/ip·udp
多多*2 小时前
线程池相关 FutureTask介绍 处理阻塞 Future改进->CompletableFuture
java·开发语言·后端·python·spring
Quantum&Coder3 小时前
Swift语言的软件工程
开发语言·后端·golang