GRS
GRS

Reputation: 3084

Django: Get all instances connected to some set of instances

I have 2 models:

class Listing:
    title = models.CharField()

class Location(models.Model):
    listing = models.ForeignKey(Listing)

Given a set of locations, l = Location.objects.all()

I want to find l.listing (Which is not the correct command)

Something like listings = Listing.objects.filter(listing_set_in=l).

It has to be as efficient as possible.

Upvotes: 1

Views: 427

Answers (1)

Andrii Rusanov
Andrii Rusanov

Reputation: 4606

If I understand you correctly, you need to find all items from Listing, that present in l queryset. To do so, you can filter Listing queryset by values from l. You can use Django subquery to reduce amount of queries.

w/ Subquery

Listing.objects.filter(pk__in=l.values('listing_id'))

The same with Subquery

from django.db.models import Subquery
Listing.objects.filter(pk__in=Subquery(l.values('listing_id')))

Upvotes: 1

Related Questions