我有一个相对简单的模型,在这个模型中,我希望将两个表中的数据作为一个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”对象和“比较器”对象都没有属性“tld”
我相信我需要创建一个expression方法来处理这个问题,但是我不确定这个表达式需要采取什么形式!
另外,如果country.tld也是hybrid_property,会有什么区别吗?
发布于 2020-03-17 07:00:11
您需要在表达式中连接字符串,在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')https://stackoverflow.com/questions/60696868
复制相似问题