【发布时间】:2015-08-01 12:07:44
【问题描述】:
如何在没有外键的情况下建立关系?
@declared_attr
def custom_stuff(cls):
joinstr = 'foreign(Custom.name) == "{name}"'.format(name=cls.__name__)
return db.relationship('Custom', primaryjoin=joinstr)
这会引发错误:ArgumentError: Could not locate any simple equality expressions involving locally mapped foreign key columns for primary join condition
这可行,但我认为这是一个非常丑陋的 hack。
@declared_attr
def custom_stuff(cls):
joinstr = 'or_(
and_(foreign(Custom.name) == MyTable.title,
foreign(Custom.name) != MyTable.title),
foreign(Custom.name) == "{name}")'.format(name=cls.__name__)
return db.relationship('Custom', primaryjoin=joinstr)
有没有更好的方法来做到这一点?
编辑:额外的属性需要添加为@declared_attr,并且必须使用关系,因为我们的序列化程序是编写的,因此它可以与声明的属性一起使用。
使用@hybrid_property 或其他方法会起作用,但我们的 json 序列化程序会中断。让它发挥作用似乎比定义关系更难。
【问题讨论】:
标签: python sqlalchemy relationship