What Happens If I Specify Onetomany Relationship Only From One Side In Flask-sqlalchemy?
Solution 1:
The brilliance behind an ORM like SQLAlchemy is that it can detect relationships between models based on foreign key constraints. So once you've declared your foreign key on the custom_job
table, the relationship is configured in the database.
Mapping that relationship to your python objects is another useful part of ORM's. Here, you are doing that with db.relationship
. By specifying backref
, you are essentially telling the ORM to make the relationship available on the other object.
Let me explain more explicitly using the code provided in your Q:
classCountry(db.Model):
__tablename__ = 'country'
...
custom_jobs = db.relationship('CustomJob', backref='custom_job', lazy=False)
...
The Country
model you've defined will map all associated rows from the custom_job
table through the attribute Country.custom_jobs
.
This relationship will propagate to the CustomJob
model and allow you to access the associated rows from the country
table through an attribute created by the backref
parameter --> here CustomJob.custom_job
.
I assume this is an error and that you intended to use
backref="country"
In this case, access associated objects instead withCustomJob.country
Post a Comment for "What Happens If I Specify Onetomany Relationship Only From One Side In Flask-sqlalchemy?"