简体   繁体   English

使用 peewee 反向外键查询

[英]Reverse foreignkey query with peewee

I'm using the peewee orm and I would like to know how to do a reverse foreignkey query.我正在使用 peewee orm,我想知道如何进行反向外键查询。

These are my models:这些是我的模型:

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

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

I would like to know the simplest way to get all the Devices that have a Metric with a field sensor="temperature".我想知道获取所有具有现场传感器 =“温度”指标的设备的最简单方法。

I can solve it with various querys and some iteration, but I wonder if there is a more direct way to do it.我可以通过各种查询和一些迭代来解决它,但我想知道是否有更直接的方法来做到这一点。

Thanks谢谢

One way:单程:

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

Another way:其它的办法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM