Django模型,每个条目具有关联的天气

时间:2019-05-20 06:12:11

标签: django django-models django-rest-framework

我有两个模型

class Route(models.Model):
    start_destination = models.CharField(max_length=255)
    end_destination = models.CharField(max_length=255)
    length_in_miles = models.CharField(max_length=255)
    ...

class Weather(models.Model):
    name = models.CharField(max_length=255)

我想像这样在Trip类中总结给定游览的所有路线

class Trip(models.Model):
    tripname = models.CharField(max_length=255)
    routes = models.ManyToManyField('Route')

但出行模型中的每条路线都应与当时的天气相关联,因此出行最终应如下所示:

tripname
routeA weatherA
routeB weatherB
routeC weatherC

我不想直接在“路线”中包含“天气”,因为同一条路线可以行驶两次,但在另一趟旅程中具有不同的天气。

1 个答案:

答案 0 :(得分:2)

我认为您可以在WeatherRoute模型之间使用具有through关系的ManyToMany关系。像这样:

import datetime

class Trip(models.Model):
    routes = models.ManyToManyField(Weather, through="TripRoute")


class TripRoute(models.Model):
     route = models.ForiegnKey(Route,related_name='weathers', on_delete=models.CASCADE)
     weather = models.ForiegnKey(Weather, related_name='routes', on_delete=models.CASCADE)
     trip = models.ForiegnKey(Trip, related_name='route_trips', on_delete=models.CASCADE)

现在,您可以在Route模型中放置一个函数来获取单个Weather实例,如下所示:

class Route(models.Model):
   ...

   def get_weather(self, date=None):
       if not date:
            date = datetime.date.today()
       return self.weathers.filter(date=date).last().weather

用法:

trip = Trip.objects.first()
routes = trip.routes.all()
for r in routes:
    r.get_weather()