背景:
使用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,