Reputation: 189
There are two models
class Question(models.Model):
text = models.TextField()
class Vote(models.Model):
cas_id = models.IntegerField()
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='votes')
I want to get ALL questions. Every question's votes set should include only votes with cas_id=123
. Some question's votes set may be empty.
SQL query looks like:
with user_votes as (
select *
from votes
where cas_id = 123
)
select *
from question q left join user_votes uv on q.id = uv.question_id;
How can I do it via django-ORM in one query?
I tried following.
.filter(votes__cas_id=123)
excludes extra rows.Upvotes: 0
Views: 50
Reputation: 653
A prefetch with a separate filter in the query should handle this:
Question.objects.all().prefetch_related(Prefetch('votes', queryset=Vote.objects.filter(cas_id=123)))
Upvotes: 1