python - 使用 peewee 进行反向外键查询

标签 python peewee

我正在使用 peewee orm,我想知道如何进行反向外键查询。

这些是我的模型:

class Device(BaseModel):
    mac = CharField()
    ip = CharField()

class Metrics(BaseModel):
    device = ForeignKeyField(Device, related_name="metrics")
    sensor = CharField()
    analog = FloatField(null = True)
    timestamp = DateTimeField()

我想知道获取所有具有传感器=“温度”字段的指标的设备的最简单方法。

我可以通过各种查询和一些迭代来解决它,但我想知道是否有更直接的方法来做到这一点。

谢谢

最佳答案

一种方法:

Device.select().join(Metric).where(Metric.sensor == 'temperature')

另一种方式:

Device.select().where(fn.EXISTS(
    Metric.select().where((Metric.sensor == 'temperature') & (Metric.device == Device.id))
))

关于python - 使用 peewee 进行反向外键查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42880977/

相关文章:

python - 使用 peewee 为带有外键的表创建唯一索引

python-3.x - peewee可以新建一个MySQL数据库吗

python - Ruby 相当于 Python 的 "dir"?

python - 如何使用 Python 重新采样

python - 类型错误 : 'str' object is not callable

python - 使用 peewee 复制对象实例并插入到数据库会创建重复的 ID

python - 使用 Peewee 库批量更新

python - 使用 SAX/Python 解析 XML + 无验证

python - 使用 str.contains 时有没有办法排除特定子字符串?

sql - 属性错误: 'bool' object has no attribute 'clone' in Peewee with SQLite