Jonathan
Jonathan

Reputation: 521

select all records from the parent table assuming something is present in the child

I'm tying to traverse up a one-to-many relationship to efficiently select all records from the parent table assuming something is present in the child table.

from models.py

class Meter(models.Model):
    deal = models.ForeignKey(Deal, on_delete=models.CASCADE)
    company = models.IntegerField()

class Deal(models.Model):
    dealinfo = models.IntegerField()

in English, select all of the deals that have meters from company #2

in SQL:

select * from Deal
where Deal.id in
(
select distinct Deal_id
from Meter
where Meter.company = 2
);

I don't know how to do this without two queries. I can't even think of a good way to google for a solution.

I tried this: result = Deal.objects.filter(meter__company=2) that I found here: How do you access parent and children relationships through the ORM with a conditional on the parent where record child exist? but it's an inner join and doesn't implement the "unique" phrase, so I get multiple records.

Upvotes: 1

Views: 43

Answers (1)

badiya
badiya

Reputation: 2257

I think what you are looking for can be solved using distinct()

 result = Deal.objects.filter(meter__company=2).distinct()

Upvotes: 2

Related Questions