Django Rest Framework可写嵌套序列化器,具有多个嵌套对象

时间:2016-02-17 19:47:29

标签: python ajax django serialization django-rest-framework

我正在尝试创建一个可写的嵌套序列化程序。我的父模型是Game,嵌套模型是Measurements。我试图使用AJAX将此数据发布到我的DRF应用程序。但是,当尝试发布数据时,嵌套的测量值为空OrderedDict()。

以下是我的模特:

class Game(models.Model):
    start_timestamp = models.DateTimeField(auto_now_add=False)
    end_timestamp = models.DateTimeField(auto_now_add=False)
    date_added = models.DateTimeField(auto_now_add=True)


class Measurement(models.Model):
    game = models.ForeignKey(Game, on_delete=models.PROTECT, related_name='measurements')
    measurement_type = models.CharField(max_length=56)
    measurement = models.CharField(max_length=56)
    timestamp = models.DateTimeField(auto_now_add=False)
    date_added = models.DateTimeField(auto_now_add=True)

以下是我的序列化程序:

class MeasurementSerializer(serializers.ModelSerializer):
        timestamp = serializers.DateTimeField(input_formats=(['%Y-%m-%d %H:%M:%S.%Z', 'iso-8601']), required=False)

        class Meta:
            model = Measurement
            fields = ('measurement_type', 'measurement', 'timestamp')


class GameSerializer(serializers.ModelSerializer):
    start_timestamp = serializers.DateTimeField(input_formats=(['%Y-%m-%d %H:%M:%S.%Z', 'iso-8601']))
    end_timestamp = serializers.DateTimeField(input_formats=(['%Y-%m-%d %H:%M:%S.%Z', 'iso-8601']))
    measurements = MeasurementSerializer(many=True)

    class Meta:
        model = Game
        fields = ('id', 'start_timestamp', 'end_timestamp', 'measurements')

    def create(self, validated_data):
        measurements = validated_data.pop('measurements')
        game = Game.objects.create(**validated_data)
        for measurement in measurements:
            Measurement.objects.create(game=game, **measurement)
        return game

我对游戏的看法如下:

class GameList(generics.ListCreateAPIView):
    queryset = Game.objects.all()
    serializer_class = GameSerializer

我跟着this tutorial了解结构。

我试图通过AJAX发布到这个API,代码如下:

 $.ajax({
         url: base_url + '/games/',
         dataType: "json",
         data: {
                "start_timestamp": "2016-02-16 14:51:43.000000",
                "end_timestamp": "2016-02-16 14:53:43.000000",
                "measurements":[
                    {'measurement_type':'type1', 'measurement':'71', 'timestamp':'2016-02-16 14:53:43.000000'},
                    {'measurement_type':'type1', 'measurement':'72', 'timestamp':'2016-02-16 14:54:43.000000'},
                    {'measurement_type':'type1', 'measurement':'73', 'timestamp':'2016-02-16 14:55:43.000000'},
                ]
                },
         type: 'POST'
     })
     .error(function(r){})
     .success(function(data){})
 });

在发布此数据时,我在GameSerializer的create方法中发现validate_data.pop('measurements')包含一个空的3个有序词典(OrderedDict())的列表。

更新:我发现通过request.data进入的initial_data结构如下:

'emotion_measurements[0][measurement_type]' (4397175560) = {list} ['type1']
'emotion_measurements[0][measurement]' (4397285512) = {list} ['71']
'emotion_measurements[0][timestamp]' (4397285600) = {list} ['2016-02-16 14:53:43.000000']
'emotion_measurements[1][measurement_type]' (4397175040) = {list} ['type1']
'emotion_measurements[1][measurement]' (4397285864) = {list} ['72']
'emotion_measurements[1][timestamp]' (4397285952) = {list} ['2016-02-16 14:54:43.000000']
'emotion_measurements[2][measurement_type]' (4397175040) = {list} ['type1']
'emotion_measurements[2][measurement]' (4397285864) = {list} ['73']
'emotion_measurements[2][timestamp]' (4397285952) = {list} ['2016-02-16 14:55:43.000000']

以前有人遇到过这个问题吗?谢谢!

更新#2

通过在MeasurementSerializer中添加以下内容,我能够解决这个问题(虽然我认为它更像是解决方法而不是解决方案):

def to_internal_value(self, data):
        formatted_data = json.dumps(data)
        formatted_data = formatted_data.replace("[", "").replace("]","")
        formatted_data = json.loads(formatted_data)
        return formatted_data

当我相信我需要一个Dict时,测量数据是一个QueryDict。键和值周围还有一些额外的括号,所以我不得不删除它们。

仍在寻求比这更好的答案!

1 个答案:

答案 0 :(得分:0)

这里的问题是在前端。默认情况下,服务器会将数据解释为application/x-www-form-urlencoded,并且为了使其了解您要向其发送json,您需要在contentType请求中指定$.ajax

$.ajax({
     url: base_url + '/games/',
     dataType: "json",
     data: {...},
     contentType: 'application/json; charset=UTF-8',  // add this line
     type: 'POST'
 })
 .error(function(r){})
 .success(function(data){});

现在,validated_data.pop('measurements') create() GameSerializer方法measurements应该与您的String str[]={"abc","defl","ghi"}; 产生三个对象(但不要忘记从更新#重做您的解决方法2)。