[英]SQLalchemy order_by hybrid_property resulting in "No such table"
[英]How to order_by hybrid_property which is a column in relationship model?
當我通過 child_field 進行查詢時,我需要訂購一些 Parent 對象。
我嘗試這樣做:
stmt = select(Parent).where([<conditions>]).options([joinedload(Parent.child)]).order_by(desc(Parent.child_field)))
# I have more options in real code
而我的模型看起來像這樣:
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")
我收到這樣的錯誤,在這里討論:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Parent.child has an attribute 'child_field'
但是解決方案我無法正確理解或不適用於我的情況。
因此,通過閱讀文檔,我得出結論,我需要編寫自定義比較器:
class CustomComparator(Comparator):
def operate(self, op, other, **kwargs):
return op(self.__clause_element__(), other, **kwargs)
並像這樣添加到父 model
# --- snip ---
@child_field.comparator
def child_field(cls):
return CustomComparator(cls.child_field)
但是這個實現當然給了我遞歸錯誤。
任何人都可以解釋什么是錯的以及如何實現我的目標,因為顯然文檔和比較器 class 內部確實解釋了我?
+
當 hybrid_property 只返回一個int
時,我是否應該使用自定義比較器來解決它?
UPD:我嘗試使用表達式而不是比較器,並停止獲取比較器 object 相關錯誤,但查詢返回未排序列表。
# ---snip---
@child_field.expression
def child_filed(cls):
return Child.child_field
應該使用表達式。 嘗試將您的表達式更改為以下內容:
@child_field.expression
def child_field(cls):
return cls.child.child_field
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.