将SQLAlchemy外键ID根据该值添加到另一个表中

时间:2018-08-02 17:30:40

标签: python database sqlalchemy flask-sqlalchemy

我有两个表:

    class User(db.Model):
        __tablename__ = 'user'

        id = db.Column(INT, primary_key=True)
        name = db.Column(db.String(16), nullable=False)
        uid = db.Column(db.String(16), unique=True)
        department_id = db.Column(INT, db.ForeignKey('department.id'), nullable=False)


    class Department(db.Model):
        __tablename__ = 'department'

        id = db.Column(INT, primary_key=True)
        name = db.Column(db.String(16), nullable=False)
        uid = db.Column(db.String(16), unique=True)

每次添加新用户时,我总是拥有其部门的name

如何仅用部门名称添加新用户,而不必查询数据库以获取department.id

1 个答案:

答案 0 :(得分:0)

如果您没有部门编号,则无法解决。常用方法:

dep = Department.query.filter_by(name=name).one()
usr = User(..., department_id=dep.id)

如果您确实想避免单独获取,也可以使用标量子查询代替id:

dep_id = db.session.query(Department.id).filter_by(name=name).as_scalar()
usr = User(..., department_id=dep_id)