【问题标题】:sqlalchemy hybrid_property joining values from a relationshipsqlalchemy hybrid_property 连接关系中的值
【发布时间】:2020-03-17 15:00:25
【问题描述】:

我有一个相对简单的模型,我想将 2 个表中的数据作为混合属性连接起来。类似于以下内容,其中global_id 将是例如fr-123de-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 数据库。

标签: python sqlalchemy


【解决方案1】:

您需要在表达式中连接字符串,在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')

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 2016-05-10
    • 2014-05-26
    • 1970-01-01
    • 2018-02-11
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多