简体   繁体   中英

Creating self-referential keys in SQLAlchemy

I am not able to create a relationship with a self-referential foreign key in SQLAlchemy. 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 .

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. 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? 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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