[英]SQLAlchemy Many-to-Many Relationship on a Single Table Error: NoReferencedTableError
I'm using Flask and SQLAlchemy. 我正在使用Flask和SQLAlchemy。
I'm trying to reference column in the same table to create a tree structure, using additional table to store all ancestor-child connections, not only parent-child. 我正在尝试引用同一表中的列以创建树结构,并使用其他表存储所有祖先连接,而不仅仅是父子连接。
I've used the example here https://stackoverflow.com/a/5652169/2947812 , and my code in models.py is: 我在https://stackoverflow.com/a/5652169/2947812使用了示例,而我在models.py中的代码是:
# -*- coding: utf-8 -*-
from my_app import db
Cats_hierarchies = db.Table('cats_hierarchies', db.MetaData(),
db.Column('parent_id', db.Integer, db.ForeignKey('category.id')),
db.Column('category_id', db.Integer, db.ForeignKey('category.id'))
)
class Category(db.Model):
__tablename__ = 'category'
id = db.Column(db.Integer, primary_key=True)
children = db.relationship("Category",
secondary = Cats_hierarchies,
primaryjoin = Cats_hierarchies.c.category_id == id,
secondaryjoin = Cats_hierarchies.c.parent_id == id,
backref="children")
When I try to create database with from my_app import db
I receive the following error message: sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'cats_hierarchies.category_id' could not find table 'category' with which to generate a foreign key to target column 'id'
当我尝试使用
from my_app import db
创建数据库时from my_app import db
收到以下错误消息: sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'cats_hierarchies.category_id' could not find table 'category' with which to generate a foreign key to target column 'id'
What am I doing wrong? 我究竟做错了什么?
I got rid of the error by adding 我通过添加摆脱了错误
foreign_keys =
[Cats_hierarchies.c.parent_id,
Cats_hierarchies.c.category_id])
to Category.children definition. 到Category.children定义。
Still don't know though why is it necessary. 仍然不知道为什么有必要。 Found it here: https://stackoverflow.com/a/8809907/2947812
在这里找到它: https : //stackoverflow.com/a/8809907/2947812
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.