首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >来自关系的sqlalchemy hybrid_property连接值

来自关系的sqlalchemy hybrid_property连接值
EN

Stack Overflow用户
提问于 2020-03-15 19:38:35
回答 1查看 341关注 0票数 1

我有一个相对简单的模型,在这个模型中,我希望将两个表中的数据作为一个hybrid_property连接起来。类似于下面的内容,其中global_id应该是fr-123de-456

代码语言:javascript
复制
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,会有什么区别吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-17 07:00:11

您需要在表达式中连接字符串,在PostgreSQL中可以使用运算符||进行连接。

代码语言:javascript
复制
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')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60696868

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档