ここに私が持っている単純なモデルがあります
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)
ここで、関連するフィールドを記録にマップしたいと思います。私はフラスコ-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 で 1 対多の関係を設定する正しい方法は何ですか。