python - 如何替换 SQLAlchemy 映射器已弃用的 "order_by"选项?

标签 python python-3.x sqlalchemy

我有一个 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/

    相关文章:

    python - 如何使用sqlalchemy调用postgresql存储过程?

    Python SQLAlchemy - 外键错误

    python - 按时间间隔分组并获取满足条件的第一行

    python - 程序在 PyCharm 中工作但在控制台中不工作,相同版本的 python

    python - 在Python中解析XML

    python - 在数组中定义多个绘图对象并在 matplotlib 动画中更新

    python-3.x - 使用 Pandas Dataframe 的 TextBlob 翻译功能时出现问题

    Python在单独的线程中执行playsound

    python - 选择一批行 sqlalchemy mysql

    python - 在同一类下通过更改 xpath 来抓取元素