如何在同时创建父级时将外键传递给序列化程序?

2024-10-01 17:39:01 发布

您现在位置:Python中文网/ 问答频道 /正文

作为开场白,我是一个初学者,我意识到我的习惯可能并不完全是标准的,所以如果你能纠正我所做的任何完全错误的事情,我将不胜感激。在

当前,我的API是使用以下方式调用的:

http:127.0.0.1:8000/weather/<latitude>,<longitude>

我从一些API中提取天气数据,但同时也希望将其存储在数据库中。为了表示天气,我有两个模型,位置当前它们保存坐标和天气信息。在本例中,父对象是Location。在

我的问题是我不知道如何将Location外键传递给CurrentlySerializer。在下面的代码中,我根本没有传递它,我收到明显的“location field is required”错误。在

视图.py

^{pr2}$

模型.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)

序列化程序.py

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = '__all__'


class CurrentlySerializer(serializers.ModelSerializer):
    class Meta:
        model = Currently
        fields = '__all__'

服务.py

def get_weather(latitude, longitude):
    response = requests.get('https://api.darksky.net/forecast/' +
                        settings.WEATHER_API_KEY + '/' +
                        latitude + ',' +
                        longitude + '/')
    return response.json()

Tags: py模型apifieldsmodels错误locationmeta
1条回答
网友
1楼 · 发布于 2024-10-01 17:39:01

您需要检索要附加到currentlyLocation实例,并将Locations主键分配给数据。在

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 the Location by latitude and longitude
    location, created = Location.objects.get_or_create(latitude=latitude, longitude=longitude, defaults={'other': 'fields', 'to': 'add', 'on': 'create')

    # Retrieve weather data.
    forecast = get_weather(latitude, longitude)
    currently = forecast['currently']

    # Assign location.pk to currently data
    currently['location'] = location.pk

    # 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)

相关问题 更多 >

    热门问题