使用sql-alchemy表类中的继承参数进行CompileError

时间:2018-02-13 23:52:21

标签: python inheritance sqlalchemy flask-sqlalchemy

我有一个继承自另一个类的SQLalchemy类(flask-sqlalchemy),看起来像这样

class Cat(db.Model, Category):
    __tablename__ = 'Cat'
    id = db.Column(db.String(1000), primary_key=True, nullable=False)
    parent_id = db.Column(db.String(1000), db.ForeignKey('SocArxivCategory.id'))

    parent_category = db.relationship('Cat',
                                      backref=db.backref('children',
                                                         order_by=Category.name,
                                                         lazy='selectin'),
                                      remote_side='Cat.id')

,父类是

class Category():
    __tablename__ = 'Category'
    name = db.Column(db.String(2000), nullable=False)

您会看到Cat表使用Category.name属性构建关系。但这似乎会导致错误

....
  File "/usr/local/lib/python2.7/site-packages/sqlalchemy/sql/compiler.py", line 692, in _fallback_column_name
    raise exc.CompileError("Cannot compile Column object until "
CompileError: Cannot compile Column object until its 'name' is assigned.

所以似乎在继承name属性之前尝试构建关系?我不确定这是SQLalchemy问题还是Python问题?知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

好的经过一些搜索和更多咨询sqlalchemy文档,我找到了解决方案。将关系的定义更改为

parent_category = db.relationship('Cat',
                                  backref=db.backref('children',
                                                     order_by=lambda: Cat.name,
                                                     lazy='selectin'),
                                  remote_side='Cat.id')

做了这个伎俩