账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Flask-SQLAlchemy如何实现带中间表的外连接查询?
    41
    0

    三张表
    其中shelf_grid是中间表,并且不是一个类

    shelf_grid = db.Table(
    'shelf_grid',
    db.Column('shelf_id', db.Integer, db.ForeignKey('plant_shelf.id')),
    db.Column('grid_id', db.Integer, db.ForeignKey('plant_grid.id')))
    
    class Grid(BaseModel, db.Model):
    __tablename__ = 'plant_grid'
    grid_code = db.Column(db.String(3), unique=True, index=True, nullable=False)
    row = db.Column(db.Integer, nullable=False)
    col = db.Column(db.Integer, nullable=False)
    shelf = db.relationship('Shelf', 
                            secondary='shelf_grid', 
                            backref=db.backref('plant_grid', lazy='dynamic'))
    
    class Shelf(BaseModel, db.Model):
    __tablename__ = 'plant_shelf'
    shelf_code = db.Column(db.String(3), unique=True, index=True, 
    nullable=False)
    total_grid = db.Column(db.Integer, nullable=False)
    surplus_grid = db.Column(db.Integer, nullable=False)

    这是我使用的SQL语句:

    select plant_grid.* from shelf_grid left join plant_grid on plant_grid.id = shelf_grid.grid_id where shelf_grid.shelf_id=1;

    要怎么通过Flask-SQLAlchemy执行这条查询语句?
    我通过以下代码执行,但是并不是Flask-SQLAlchemy。获得的grid_code是bytes类型的,而我希望获得的是str类型。此外,我还需要使用paginate()。所以使用以下代码实现功能并不是一个好的选择。

    result = db.session.execute("select plant_grid.* from shelf_grid "
                                "left join plant_grid on 
                                 plant_grid.id=shelf_grid.grid_id "
                                "where shelf_grid.shelf_id=1")
    for grid in result:
        print(grid.grid_code) # print b'001'...
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部