【问题标题】:SQLAlchemy query filter by field value in related tableSQLAlchemy 查询按相关表中的字段值过滤
【发布时间】:2018-09-25 20:14:01
【问题描述】:

我尝试获取类型不是'TYPE_BLADE_SERVER' 的设备。请帮忙写一个查询。我尝试的解决方案:

result = Device.query.filter(DeviceGroup.type != ModelType.TYPE_BLADE_SERVER).all()

没有过滤 device_group 表因为 device_group 重命名为 device_group_1。来自 sqlalchemy 的 Sql 查询:

SELECT * FROM device_group, device
LEFT OUTER JOIN device_model AS device_model_1 ON device_model_1.id = device.model_id
LEFT OUTER JOIN device_group AS device_group_1 ON device_group_1.id = device_model_1.group_id 
WHERE device_group.type != % (type_1)s ; {'type_1': 'TYPE_BLADE_SERVER'}

可行的解决方案,但喜欢 sql 硬编码:

result = Device.query.filter(text("device_group_1.type <> 'TYPE_BLADE_SERVER'")).all()

我的模型:

class Device(db.Model):
    __tablename__ = 'device'

    id = db.Column(db.Integer, primary_key=True)
    hostname = db.Column(db.String, index=True)
    model_id = db.Column(db.ForeignKey('device_model.id'), nullable=True)
    model = db.relationship("DeviceModel", backref='devices', lazy='joined')

class DeviceModel(db.Model):
   __tablename__ = 'device_model'

   id = db.Column(db.Integer, primary_key=True)
   group_id = db.Column(db.ForeignKey('device_group.id', ondelete='SET NULL'), nullable=True)

class DeviceGroup(db.Model):
    __tablename__ = 'device_group'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False, unique=True)
    height = db.Column(db.Integer, nullable=False)
    models = db.relationship("DeviceModel", backref=backref("group", lazy="joined"), lazy='joined')
    type = db.Column(sa.Enum(ModelType), nullable=False)

class ModelType(enum.Enum):
    TYPE_BLADE_SERVER = 'TYPE_BLADE_SERVER'
    TYPE_ENGINEERING_DEVICES = 'TYPE_ENGINEERING_DEVICES'
    TYPE_DATA_STORAGE = 'TYPE_DATA_STORAGE'

【问题讨论】:

    标签: python sqlalchemy flask-sqlalchemy


    【解决方案1】:

    你不需要_

    from sqlalchemy import not_
    result = Device.query.filter(not_(DeviceGroup.type == ModelType.TYPE_BLADE_SERVER)).all()
    or
    result = Device.query.filter(~DeviceGroup.type == ModelType.TYPE_BLADE_SERVER)
    

    【讨论】:

    • 运算符不等于!=。表达式 ~DeviceGroup.type 使用 sql WHERE (NOT device_group.type) = %(param_1)s' 产生错误我认为我的表命名有问题。感谢重播。
    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2023-03-05
    • 2015-10-20
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多