flask-sqlalchemy的模型类两个表,既有一对一又有一对多的情况时,解决方法

这种情况时,直接进行数据迁移会回报错,因为一个表需要依赖另一个表,所以可以将两个表的基本字段先迁移好,然后再新增外键字段进行迁移,就不会报错了
from datetime import datetime

from api.models.base import BaseModel
from api import db
from werkzeug.security import check_password_hash, generate_password_hash
import enum



class MyEnum(enum.Enum):
    UN_ACTIVE = 0  # 没有激活
    ACTIVE = 1  # 已经激活的
    LOCKED = 2  # 被锁定


class User(BaseModel, db.Model):
    __tablename__ = 'user'
    __table_args__ = {'comment': '用户表'}
    id = db.Column(db.Integer, primary_key=True, comment='用户id')
    realname = db.Column(db.String(12), unique=True, nullable=False, comment="用户名")
    pwd = db.Column(db.String(240), nullable=False, comment="用户密码")
    email = db.Column(db.String(20), unique=True, nullable=False, comment="用户邮箱")
    telephone = db.Column(db.String(20), comment="用户电话")
    is_staff = db.Column(db.Boolean, default=True, comment="是否为员工")
    status = db.Column(db.Enum(MyEnum), default=MyEnum.UN_ACTIVE, comment="员工状态")
    date_joined = db.Column(db.DateTime, default=datetime.now, comment="入职时间")

    # 员工所属的部门(多对一)
    department_id = db.Column(db.Integer, db.ForeignKey('department.id', ondelete='CASCADE'))

    # 领导所属的部门(多对一或一对一)
    leader_id = db.Column(db.Integer, db.ForeignKey('department.id', ondelete='CASCADE'))

    # 关系:员工对应的部门
    staffs_department = db.relationship('Department', back_populates='staffs', foreign_keys=[department_id])

    # 关系:领导对应的部门
    leader_department = db.relationship('Department', back_populates='leader', foreign_keys=[leader_id])




class Department(BaseModel, db.Model):
    __tablename__ = 'department'
    __table_args__ = {'comment': '部门表'}
    id = db.Column(db.Integer, primary_key=True, comment='部门id')
    name = db.Column(db.String(20), nullable=False, unique=True, comment='部门名称')
    intro = db.Column(db.Text, comment='部门介绍')
    staff_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    # 一对多关系,表示这个部门的员工
    staffs = db.relationship('User', back_populates='staffs_department', lazy='dynamic', cascade='all, delete',
                             passive_deletes=True, foreign_keys='User.department_id')

    # 一对一关系,表示这个部门的领导
    leader = db.relationship('User', back_populates='leader_department', uselist=False, foreign_keys='User.leader_id')

你可能感兴趣的:(Flask,python)