Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query that sorts models according to date of parent model

Say I have three models that represent a football team, a football team event, and an event location. Each football team has multiple events. Not every event has a location.

class FootballTeam(models.Model):

    team_name = models.CharField()

    def get_latest_location(self):

        # ???

class Event(models.Model):

    team = models.ForeignKey(FootballTeam)
    time = models.DateField()

class EventLocation(models.Model):

    event = models.ForeignKey(Event)
    location_name = models.CharField()

How do I write a Django query to retrieve the latest EventLocation of a FootballTeam? In other words, how do I sort a set of models according to the date of a parent model?

like image 760
mario_sunny Avatar asked Sep 26 '22 19:09

mario_sunny


1 Answers

def get_latest_location(self):
    return EventLocation.objects.filter(event__team=self).order_by("-event__time").first()
like image 140
Ozgur Vatansever Avatar answered Oct 05 '22 23:10

Ozgur Vatansever