我有一个 Single Table Inheritance
看起来像这样的 sqlalchemy orm 模型:
class Human(Base):
__tablename__ = "human"
id = Column(Integer, primary_key=True)
name = Column(String)
index = Column(Integer)
parent_id = Column(Integer, ForeignKey("human.id"), nullable=True)
type = Column(String)
parent = relationship(
"Human",
cascade="save-update, merge",
backref=backref("children", cascade="all"),
lazy=False,
remote_side="Human.id",
)
__mapper_args__ = {"polymorphic_on": type, "polymorphic_identity": "human"}
class Parent(Human):
__mapper_args__ = {"polymorphic_identity": "parent"}
class Child(Human):
hobby = Column(String)
pet = Column(String)
__mapper_args__ = {"polymorphic_identity": "child"}
这种关系看起来像一个嵌套的树,我可以在其中查询最年长的人(即:曾祖 parent ,使用 query.get(1)
),然后查询他的 children
归他所有children
将出席,每个 child 也将有他们的children
展示。这种关系在各个方面都运行良好。
我想要
children
当我查询 Parent
时所查询的(由于lazy=False)由index
订购列不是id
列(这是默认值)。我通过添加以下内容来实现这一点
"order_by": "index"
到 Human
类(class)'__mapper_args__
如下:__mapper_args__ = {"polymorphic_on": type, "polymorphic_identity": "human", "order_by": "index"}
我最近发现在 SQLAlchemy 中 order_by
mapper()
中的参数自 SQLAlchemy 版本 1.1
起不推荐使用类( reference )。他们说要使用 Query.order_by()
改为订购该套装,但由于某种原因这对我不起作用。我尝试了以下方法:
order_by
到查询,session.query(Human).order_by(Human.index).get(1)
order_by="Human.index"
到 relationship()
在 Human
类(class)。 这两种方法都行不通。
我怎样才能达到和
order_by
一样的效果在 mapper()
现在它正在被弃用?
最佳答案
我在 sqlalchemy's github 上提问后得到了答案.
我正在提出响应,以防其他人搜索此问题并在此处而不是 sqlalchemy 的 github 中找到它。
The answer:
the ordering of a collection loaded by a relationship is controlled by the order_by parameter of relationship() and/or backref. In this case you want "children" to be ordered so you put that where you define "children":
parent = relationship( "Human", cascade="save-update, merge", backref=backref("children", cascade="all", order_by="Human.index"), lazy=False, remote_side="Human.id", )
that is, this has nothing to do with mapper.order_by, although that attribute was having the effect you were seeking. if you had tried relationship->order_by on the "parent' side, that was the wrong side, it goes where the actual thing to be ordered is defined, in this case the backref.
关于python - 如何替换 SQLAlchemy 映射器已弃用的 "order_by"选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65872223/