具有多个连接的SQLAlchemy ORM load_only列

时间:2018-09-14 10:26:02

标签: python sqlalchemy flask-sqlalchemy

现在我有:

class DeviceModel(db.Model):

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

class DeviceGroup(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False, unique=True)
    device_type_id = db.Column(db.ForeignKey('device_type.id', ondelete='SET NULL'), nullable=True)
    device_type = db.relationship("DeviceType", lazy='joined')

class DeviceType(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False, unique=True)

如何仅查询DeviceModel.idDeviceType.name字段?

在纯sql中,是:

SELECT device_model.id               AS device_model_id,
       device_type_1.name            AS device_type_1_name
FROM device_model
       LEFT OUTER JOIN device_group AS device_group_1 ON device_group_1.id = device_model.group_id
       LEFT OUTER JOIN device_type AS device_type_1 ON device_type_1.id = device_group_1.device_type_id;

0 个答案:

没有答案