假设我有三个代表足球队,足球队赛事和赛事位置的模特。每个足球队都有多个赛事。并非每个活动都有位置。
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()
如何编写Django查询以检索FootballTeam的最新 EventLocation?换句话说,如何根据父模型的日期对一组模型进行排序?
答案 0 :(得分:4)
def get_latest_location(self):
return EventLocation.objects.filter(event__team=self).order_by("-event__time").first()