Reputation: 3519
class Event(HashidModel, TimeStampedModel):
organizer = models.ForeignKey(
"organizers.Organizer", on_delete=models.CASCADE, related_name="events"
)
How do I get all organizers, that have existing events? My challenge is that I have to go through the organizer (I can't start from the event mode.l)
organizer = Organizer.objects.all()
Upvotes: 1
Views: 24
Reputation: 477035
You can filter with:
Organizer.objects.filter(
events__isnull=False
).distinct()
This works since we perform a LEFT OUTER JOIN
on the Event
table, and then filter such that we only retrieve items for wich the id
of the Event
is NOT NULL
. We then take the DISTINCT
objects to avoid retrieving the Organizer
multiple times, one per Event
.
Normally Django will optimize this to an INNER JOIN
.
Upvotes: 2