我试图在三个单独的文件中的三个模型类之间创建多对多关系:用户,项目和付款(这是关联类),但是我一直收到此错误:
sqlalchemy.exc.NoReferencedColumnError: Could not initialize target column for ForeignKey 'projects.id,' on table 'payments': table 'projects' has no column named 'id,'
尝试调试几天后,我相信我的问题是我没有元数据对象:“根据相关性对相关表进行排序,以便可以按正确的顺序创建外键约束。”在此处讨论:Understanding MetaData() from SQLAlchemy in Python
那么,如何设置元数据对象并对表进行排序,以便在各个文件中以正确的顺序创建外键约束?如果这样做,它将解决NoReferencedColumnError吗?
这是我的模型类(付款类发生错误):
class User(UserMixin, ResourceMixin, db.Model):
ROLE = OrderedDict([
('member', 'Member'),
('admin', 'Admin')
])
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
# Relationships.
payments = db.relationship(
'Project', secondary='payments',
backref=db.backref('payees', lazy='dynamic')
)
class Project(ResourceMixin, db.Model):
__tablename__ = 'projects'
id = db.Column(db.Integer, primary_key=True)
# Relationships.
users = db.relationship('User', secondary="payments")#backref='users')
fund = db.Column(db.Integer, unique=False, index=True, server_default='0')
goal = db.Column(db.Integer, nullable=False, server_default='15000')
class Payment(ResourceMixin, db.Model):
__tablename__ = 'payments'
id = db.Column(db.Integer, primary_key=True)
# Payment details.
user_id = db.Column(db.Integer, db.ForeignKey('users.id',
onupdate='CASCADE',
ondelete='CASCADE'),
index=True, nullable=False)
project_id = db.Column(db.Integer, db.ForeignKey('projects.id,'))
amount = db.Column(db.Integer) #Error occurs on this line.
# Relationships.
user = db.relationship('User', backref='payments')
project = db.relationship('Project', backref='payments')