我对SQLAlchemy不熟悉,并且在涉及外键时如何创建hybrid_property
表达式有点困惑。以下是我正在使用的声明性类:
class ProductColor(Base):
__tablename__ = 'productcolor'
value = Column(Text, nullable=False, unique=True)
rgb = Column(Text, nullable=False)
cmyk = Column(Text)
class ProductVariant(Base):
__tablename__ = 'productvariant'
product_id = Column(Integer, ForeignKey('product.id'),
nullable=False)
product = relationship('Product', backref='variants')
color1_id = Column(Integer, ForeignKey(ProductColor.id), nullable=False)
color1 = relationship(ProductColor, foreign_keys=color1_id)
color2_id = Column(Integer, ForeignKey(ProductColor.id))
color2 = relationship(ProductColor, foreign_keys=color2_id)
is_display_color = Column(Boolean, default=False)
@hybrid_property
def slug(self):
return u''.join((self.color1.value, getattr(self.color2, 'value', '')))
@slug.expression
def slug(cls):
pass # What do i write here?
实例属性工作正常,但我不确定要在表达式属性中放入什么。我尝试了以下内容,但它给了我AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with ProductVariant.color1 has an attribute 'value'
:
@slug.expression
def slug(cls):
return cls.color1.value + cls.color2.value
修改
我也尝试过以下内容,然后获取AttributeError: 'str' object has no attribute 'corresponding_column'
:
@slug.expression
def slug(cls):
color1 = aliased(ProductColor, 'color1')
color2 = aliased(ProductColor, 'color2')
return (select([func.concat(color1.value, color2.value)])
.join(color1).filter(color1.value == cls.color1.value)
.outerjoin(color2).filter(color2.value == cls.color2.value)
.as_scalar())
你们对此有什么好的解决方案吗?