仅作为序言,我是初学者,我意识到我的约定可能不完全是标准的,所以如果你能纠正我做错的话,我将不胜感激。
目前,我的API使用以下方式调用:
http:127.0.0.1:8000/weather/<latitude>,<longitude>
我从某些API中提取天气数据,但也希望同时将其存储在数据库中。为了表示天气,我有两个模型,位置和当前,它们包含坐标和天气信息。在这种情况下,父级是位置。
我的问题是我不知道如何将 Location 外键传递给 CurrentlySerializer 。在下面的代码中,我根本没有传递它,我收到了明显的&#34;位置字段是必需的&#34;错误。
views.py
def get(self, request, *args, **kwargs):
# Process latitude and longitude coordinates from URL
coordinates = kwargs.pop('location', None).split(",")
latitude = coordinates[0]
longitude = coordinates[1]
# Retrieve weather data.
forecast = get_weather(latitude, longitude)
currently = forecast['currently']
# Serialize and confirm validity of data.
location_serializer = LocationSerializer(data=forecast)
if not location_serializer.is_valid():
return Response(location_serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
currently_serializer = CurrentlySerializer(data=currently)
if not currently_serializer.is_valid():
return Response(currently_serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
response = location_serializer.data + currently_serializer.data
return Response(response, status=status.HTTP_200_OK)
models.py
class Location(models.Model):
... some fields
class DataPoint(models.Model):
... some fields
class Meta:
abstract = True
class Currently(DataPoint):
location = models.ForeignKey(Location, on_delete=models.CASCADE)
serializers.py
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = '__all__'
class CurrentlySerializer(serializers.ModelSerializer):
class Meta:
model = Currently
fields = '__all__'
services.py
def get_weather(latitude, longitude):
response = requests.get('https://api.darksky.net/forecast/' +
settings.WEATHER_API_KEY + '/' +
latitude + ',' +
longitude + '/')
return response.json()
答案 0 :(得分:1)
您需要检索要附加到Location
的{{1}}实例,并将currently
主键分配给数据。
Locations