What happens if I specify OneToMany relationship only from one side in flask-sqlalchemy?

社会主义新天地 提交于 2021-01-28 11:41:43

问题


I have a OneToMany relationship between 2 entities in flask. I also specified the relationship only on one side. I am unsure what the difference is between the following:

class CustomJob(db.Model):
    __tablename__ = "custom_job"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    country_from = db.Column(db.Integer, db.ForeignKey('country.id'))

class Country(db.Model):
    __tablename__ = "country"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    custom_jobs = db.relationship('CustomJob', backref="country", lazy=False)

Or just specify the foreign key on master entity:

class CustomJob(db.Model):
    __tablename__ = "custom_job"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    country_from = db.Column(db.Integer, db.ForeignKey('country.id'))

will is there performance difference between the two ?


回答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:

class Country(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 with CustomJob.country



来源:https://stackoverflow.com/questions/65369287/what-happens-if-i-specify-onetomany-relationship-only-from-one-side-in-flask-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!