这是我的简单模型
class Record(db.Model):
__tablename__ = 'reg_records'
request_id = db.Column(db.Integer, primary_key = True)
title = db.Column(NVARCHAR())
class Field(db.Model):
__tablename__ = 'reg_fields'
request_id = db.Column(db.Integer, primary_key= True)
name = db.Column(NVARCHAR(), primary_key = True)
现在我想将相关字段映射到记录。我正在遵循 flask-sqlalchemy 规范并得到这个
class Field(db.Model):
__tablename__ = 'reg_fields'
request_id = db.Column(db.Integer, ForeignKey('record.request_id'), primary_key= True)
name = db.Column(NVARCHAR(), primary_key = True)
class Record(db.Model):
__tablename__ = 'reg_records'
request_id = db.Column(db.Integer, primary_key = True)
title = db.Column(NVARCHAR())
fields = db.relationship(Field, backref = 'record')
但是,当我尝试使用此模型时,出现以下错误
sqlalchemy.exc.NoForeignKeysError
NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Record.fields - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
添加primaryjoin
到如下关系声明
fields = db.relationship(Field, backref = 'record', primaryjoin='Record.request_id==Field.request_id')
没有解决问题,而是给出了新的异常
sqlalchemy.exc.NoReferencedTableError
NoReferencedTableError: Foreign key associated with column 'reg_fields.request_id' could not find table 'record' with which to generate a foreign key to target column 'request_id'
如果我用 primaryjoin 值中的表名替换类名,
fields = db.relationship(Field, backref = 'record', primaryjoin='reg_records.request_id==reg_fields.request_id')
我又遇到了一个例外
sqlalchemy.exc.InvalidRequestError
InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Original exception was: 'Table' object has no attribute 'request_id'
总的来说,在 flask-sqlalchemy 中建立一对多关系的正确方法是什么。