I have two models, Location
and Event
, that are linked by ForeignKey on the Event
model. The models break down as follows:
class Location(models.Model):
city = models.CharField('city', max_length=25)
slug = models.SlugField('slug')
class Event(models.Model):
location = models.ForeignKey(Location)
title = models.CharField('title', max_length=75)
start_date = models.DateTimeField('start_date')
end_date = models.DateTimeField('end_date')
Each location has multiple events that are ordered by start_date
descending. The query I am trying to make retrieves the next upcoming event for each of the locations.
Ideally I would like to make this in a single query (I don't want to run a query for every location, as this would cause a lot of unnecessary hits to the database). I have tried using Django's ORM, and I've also tried using raw SQL, but I've hit a bit of a roadblock.
Any help would be greatly appreciated.
Update
I have come up with a potential solution, though I'm not convinced that it's the best method. It works, which should be enough, but I'm curious to see what the best method of doing this would be.
Anyway, the code I've written reads thus:
l = Location.objects.select_related()
qs = None
# Concatenate the related event querysets into a new queryset
for e in l:
if qs is None:
qs = e.event_set.all()
else:
qs = qs | e.event_set.all()
# Order a slice of the queryset by start_date ascending
qs = sorted(qs[:l.count()], key=lambda s: s.start_date)