[英]sqlalchemy hybrid_property joining values from a relationship
我有一個相對簡單的模型,我想在其中將 2 個表中的數據連接為一個 hybrid_property。 類似於以下內容,其中global_id
將是fr-123
或de-456
。
class Product(Base):
product_id = Column(Integer, primary_key=True)
country_id = Column(Integer, ForeignKey('country.id'), nullable=False)
country = relationship('Role', backref='product')
@hybrid_property
def global_id(self):
return self.country.tld + "-" + self.product_id
這適用於簡單的查詢,但是當我嘗試使用LIKE
進行搜索時,出現錯誤:
AttributeError: 與 Product.country 關聯的“InstrumentedAttribute”對象和“Comparator”對象都沒有屬性“tld”
我相信我需要創建一個expression
方法來處理這個問題 - 但我不確定該表達式需要采用什么形式!
如果country.tld
也是hybrid_property
也會有所不同嗎?
您需要在表達式中連接字符串,在 PostgreSQL 中您可以使用運算符||
:
from sqlalchemy.sql import select
class Country(Base):
__tablename__ = 'country'
id = Column(Integer, primary_key=True)
tld = Column(String)
class Product(Base):
__tablename__ = 'product'
product_id = Column(Integer, primary_key=True)
country_id = Column(Integer, ForeignKey('country.id'), nullable=False)
country = relationship('Country', backref='product')
@hybrid_property
def global_id(self):
return self.country.tld + "-" + str(self.product_id)
@global_id.expression
def global_id(cls):
return select([Country.tld.op('||')('-').op('||')(cls.product_id)]).\
where(Country.id==cls.country_id).label('global_id')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.