[英]Creating self-referential keys in 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
为NOT NULL的行, parent_category
属性为None
。
上表中我将有多个自引用外键,但是我首先要使其与一个自引用外键一起使用。
您不必使用简单的forinin键定义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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.