Here is simple model I have
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)
Now I want to map releated fields to record. I'm following flask-sqlalchemy specs and getting this
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')
However when I try to use this model I'm getting following error
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.
Adding primaryjoin to the relationship declaration like below
fields = db.relationship(Field, backref = 'record', primaryjoin='Record.request_id==Field.request_id')
Doesnt solve the problem, but instead gives new exception
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'
If I replace class names with table names in primaryjoin value,
fields = db.relationship(Field, backref = 'record', primaryjoin='reg_records.request_id==reg_fields.request_id')
I'm getting one another exception
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'
Overall, what is right way setting up one-to-many relationship in flask-sqlalchemy.