SqlAlchemy:可以在关系中使用混合表达式吗?

我试图在primaryjoin将使用远程类的@ .expression(混合表达式)属性的模型中建立关系。 代码如下所示:

class LCProduct(db.Model):
    __tablename__ = 'lcproduct'

    product_id = Column(Integer,
                        Sequence('lcproductcategory_seq'),
                        primary_key=True)
    label               = Column(String)
    category            = relationship('LCCategory', primaryjoin='LCProduct.label == LCCategory.label')

class LCCategory(db.Model):
    __tablename__ = 'lccategory'

    category_id         = Column(Integer, primary_key=True)
    category_type       = Column(String)
    display_name        = Column(String)

    @hybrid_property
    def label(self):
        retval = '{category_type}: {display_name}' 
            .format(category_type=self.category_type, display_name=self.display_name)
        return retval

    @label.expression
    def label(cls):
        return func.concat(cls.category_type, func.concat(': ', cls.display_name))

在上面的代码中,LCProduct类有一个只是一个字符串的“标签”列。 这个字符串以这种方式等于LCCategory中的两列:

{category_name}:{display_name}

两列之间用':'连接。 这就是@ label.expression所做的。 但是,当我运行包含此代码的程序(LCProduct中的关系)时,出现如下所示的长错误消息:

InvalidRequestError:一个或多个映射器无法初始化 - 无法继续初始化其他映射器。 触发映射器:'映射器| LCProductCategory | lcproductcategory'。 原始异常是:无法为关系LCProductCategory.category上的主要连接条件'lcproductcategory.label = concat(lccategory.category_type,concat(:concat_1,lccategory.display_name))'找到任何相关外键列。 确保引用列与ForeignKey或ForeignKeyConstraint关联,或者在连接条件中使用foreign()注释进行注释。

我试图做甚至可能吗?

在此先感谢您的帮助!

道格

链接地址: http://www.djcxy.com/p/63439.html

上一篇: SqlAlchemy: is it possible to use a hybrid expression in a relationship?

下一篇: Understanding repr( ) function in Python