定义没有外键的关系

zid*_*sk8 7 python sqlalchemy relationship

如何在没有外键的情况下建立关系?

@declared_attr 
def custom_stuff(cls): 
    joinstr = 'foreign(Custom.name) == "{name}"'.format(name=cls.__name__)  
    return db.relationship('Custom', primaryjoin=joinstr) 
Run Code Online (Sandbox Code Playgroud)

这引发了一个错误:
ArgumentError: Could not locate any simple equality expressions involving locally mapped foreign key columns for primary join condition

这有效,但我认为这是一个非常丑陋的黑客.

@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)
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

编辑:额外的属性需要添加为@declared_attr必须使用关系,因为我们的序列化程序是编写的,因此它适用于声明的attrs.

@hybrid_property其他东西做这件事会有效,但是我们的json序列化器会破坏.让它发挥作用似乎比定义关系更难.

小智 -2

也许你应该指出“关系”这个词的含义。它指出某事物“依赖于”其他事物或两者相互依赖。如果您尝试在 ERM(实体关系模型)上定义关系,这意味着您应该声明哪个实体“依赖”另一个实体。此外,数据库还有一些技巧可以更快地处理相互关联的表,而不仅仅是以上层抽象方式关联的简单表。您有什么理由需要这样做吗?