简体   繁体   English

如何按关系 model 中的列的 hybrid_property 排序?

[英]How to order_by hybrid_property which is a column in relationship model?

I need to order some Parent objects when i do query by child_field.当我通过 child_field 进行查询时,我需要订购一些 Parent 对象。
I try to do it like this:我尝试这样做:

stmt = select(Parent).where([<conditions>]).options([joinedload(Parent.child)]).order_by(desc(Parent.child_field)))
# I have more options in real code

while my models looks like these:而我的模型看起来像这样:

class Parent(Base):
    __table_name___ = "parent"
    some_field = Column(String(256))
    child = relationship("Child", back_populates="parent")])

    @hybrid_property
    def child_field(self):
        return self.child.child_field

class Child(base):
    child_field = Column(Integer)
    parent = relationship("Parent", back_populates="child")

I get error like this which discussed here :我收到这样的错误,在这里讨论:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Parent.child has an attribute 'child_field'

However solution I can't properly understand or it's not apply in my case.但是解决方案我无法正确理解或不适用于我的情况。

So by reading docs i concluded that I need to write custom comparator:因此,通过阅读文档,我得出结论,我需要编写自定义比较器:

class CustomComparator(Comparator):
    def operate(self, op, other, **kwargs):
        return op(self.__clause_element__(), other, **kwargs)

and added like this to parent model并像这样添加到父 model

# --- snip ---
    @child_field.comparator
    def child_field(cls):
        return CustomComparator(cls.child_field)

But this implementation gives me recursion error of course.但是这个实现当然给了我递归错误。

Can anyone explain what's wrong and how to achieve my goal because apparently docs nor Comparator class insides does explain it me?任何人都可以解释什么是错的以及如何实现我的目标,因为显然文档和比较器 class 内部确实解释了我?
+ +
Should I even solve it with custom comparator when hybrid_property returns just an int ?当 hybrid_property 只返回一个int时,我是否应该使用自定义比较器来解决它?

UPD: I tried use expression instead of comparator, and stopped getting comparator object related error, however query return not ordered list. UPD:我尝试使用表达式而不是比较器,并停止获取比较器 object 相关错误,但查询返回未排序列表。

# ---snip---
@child_field.expression
def child_filed(cls):
    return Child.child_field

Should be working with an expression.应该使用表达式。 Try to change your expression to the following:尝试将您的表达式更改为以下内容:

@child_field.expression
def child_field(cls):
    return cls.child.child_field

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM