Django request that sorts models according to the date of the parent model

Let's say I have three models that represent a soccer team, a soccer team event, and an event venue. Each football team has several events. Not every event takes place.

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 to write a Django request to get the latest EventLocation event in FootballTeam? In other words, how do I sort a set of models according to the date of the parent model?

+5
source share
1 answer
 def get_latest_location(self): return EventLocation.objects.filter(event__team=self).order_by("-event__time").first() 
+4
source

Source: https://habr.com/ru/post/1239614/


All Articles