Reputation: 183
I'm using the peewee orm and I would like to know how to do a reverse foreignkey query.
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
Upvotes: 2
Views: 545
Reputation: 26225
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))
))
Upvotes: 2