是否可以使用flask_sqlalchemy在烧瓶的单独的.py文件中具有dabase模型

时间:2019-11-29 11:06:56

标签: python flask sqlalchemy flask-sqlalchemy

根据我对如何构造flask应用程序的示例所做的研究,它得出的经验法则是将所有数据库模型都放在一个文件models.py

是否可以将模型存储在名为models的目录中,并且其中的模型分别有users.pycompany.py,它们分别具有定义的表名和数据库结构,即列。 >

您又如何定义两者之间的数据库关系,例如one-to-many关系,即公司可以拥有许多用户,并且避免在定义数据库关系时在两个文件之间导入 circular 导入错误。

一个例子是

models/users.py

from app import db
import company

class User(db.Model):
    """This class represents the User Table"""

    __tablename__ = 'users'


    #Define the column of the user table
    user_id = db.Column(db.Integer,primary_key=True)
    company_id = db.Column(db.Integer, 
       db.ForeignKey(company.Company.company_id)) 

然后在models/company.py

from app import db
import users

class Company(db.Model):
    """This class represents the Company Table"""

    __tablename__ = 'companies'


    #Define the column of the company table
    company_id = db.Column(db.Integer,primary_key=True)
    user = db.relationship(
        'users.User',order_by='users.User.user_id',cascade="all ,delete-orphan", 
         backref="candidate" ,lazy="dynamic")

0 个答案:

没有答案