[英]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.