在SQLAlchemy中创建自引用键

时间:2014-07-30 07:26:24

标签: python sqlalchemy

我无法在SQLAlchemy中使用自引用外键创建relationship。我的模型看起来像:

class Category(db.Model):
     __tablename__ = 'categories'

     category_id = db.Column(db.Integer, primary_key = True, autoincrement = False)
     name = db.Column(db.String(50), unique = True)
     parent_category_id = db.Column(db.Integer, db.ForeignKey('categories.category_id'))

     parent_category = relationship('Category', primaryjoin = ('Category.parent_category_id == Category.category_id'), uselist = False)

使用此架构创建表,我可以在表中插入行。但对于parent_category_id为非NULL的行,parent_category属性为None

我将在上表中有多个自引用foreigns键,但我首先要使用一个自引用外键来处理它。

1 个答案:

答案 0 :(得分:0)

您不必使用简单的foregin键定义primaryjoin。这就是我要做的事情

parent_category = relationship(
    'Category',
    uselist=False,
    foreign_keys=[parent_category_id],
    remote_side=[id],
    cascade='save-update',
    backref=backref(
        'children_categories',
        uselist=True,
        order_by="Category.name",
        cascade='save-update',
    )
)

为什么您的解决方案无效?我认为无法从中推断出你的意思

primaryjoin = ('Category.parent_category_id == Category.category_id')

SQLAlchemy如何知道你的意思是两个不同的类别?怎么知道哪个是"这里"那边是"那里"侧?

如果由于某种原因你需要使用primaryjoin,这就是解决问题的方法

parent_category = relationship(
    'Category',
    primaryjoin=parent_category_id == category_id,
    foreign_keys=parent_category_id,
    remote_side=category_id
)
相关问题