简体   繁体   English

在SQLAlchemy中创建自引用键

[英]Creating self-referential keys in SQLAlchemy

I am not able to create a relationship with a self-referential foreign key in SQLAlchemy. 我无法在SQLAlchemy中使用自引用外键创建relationship My model looks like: 我的模型如下:

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)

The table does get created with this schema and I am able to insert rows into the table. 该表确实是使用此架构创建的,并且我能够在表中插入行。 But for a row whose parent_category_id is NOT NULL, the parent_category attribute is None . 但是对于parent_category_id为NOT NULL的行, parent_category属性为None

I will have multiple self-referential foreigns keys in the above table but I am first working on getting it to work with one self-referential foreign key. 上表中我将有多个自引用外键,但是我首先要使其与一个自引用外键一起使用。

You do not have to define primaryjoin with a simple foregin key. 您不必使用简单的forinin键定义primaryjoin。 Here is what I would do 这是我会做的

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',
    )
)

Why your solution doesn't work? 为什么您的解决方案不起作用? I think there is no way to deduce what you mean from 我认为无法从中推断出您的意思

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

How is SQLAlchemy supposed to know that you mean two different Categories? SQLAlchemy应该如何知道您的意思是两个不同的类别? How is it supposed to know which is on the "here" side and which is on "there" side? 应该如何知道哪个在“这里”一侧,哪个在“那里”一侧?

If for some reason you need to use primaryjoin , this is how to fix it 如果由于某种原因需要使用primaryjoin ,这是解决方法

parent_category = relationship(
    'Category',
    primaryjoin=parent_category_id == category_id,
    foreign_keys=parent_category_id,
    remote_side=category_id
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM