Django将两个值序列化/反序列化为一个模型字段

时间:2017-02-26 08:17:39

标签: django serialization django-rest-framework

我有这段代码:

models.py

from django.contrib.gis.db import models

class Driver(models.Model):
    location = models.PointField(null=True, blank=True)
    accuracy = models.DecimalField(max_digits=10, decimal_places=3)

serializers.py

from rest_framework import serializers
from .models import Driver

class DriverSerializer(serializers.ModelSerializer):
    class Meta:
        model = Driver
        fields = '__all__'

PointField被序列化为

{"location":"SRID=4326;POINT (106.84341430665 -6.1832427978516)"} 

但我想得到

{"latitude": 106.84341430665, "longitude": -6.1832427978516}

序列化时,也使用此格式进行反序列化。是否可以在序列化器中执行此操作?

2 个答案:

答案 0 :(得分:2)

谢谢masnun指向正确的方向。这就是我想出的:

from rest_framework import serializers
from django.contrib.gis.geos import Point
from .models import Driver

class DriverSerializer(serializers.ModelSerializer):
    location = serializers.SerializerMethodField()
    latitude = serializers.FloatField()
    longitude = serializers.FloatField()
    class Meta:
        model = Driver
        fields = '__all__'

    def get_location(self, obj):
        return Point(obj.latitude, obj.longitude)    

    def to_representation(self, instance):
        ret = super(DriverSerializer, self).to_representation(instance)
        lat, lon = ret['location'].coords
        ret['latitude'] = lat
        ret['longitude'] = lon
        del ret['location']
        return ret

反序列化(json - &gt;模型)通过向DriverSerializer添加两个新字段来处理,覆盖现有的&#34;位置&#34; SerializerMethodField字段并实施get_<field_name>http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

to_representation处理序列化(model - &gt; json)部分。

答案 1 :(得分:1)

您可以使用两个序列化方法字段,该字段接受obj作为第二个参数。然后,您可以使用这些方法处理longitudelatitude

您还可以编写自定义序列化程序字段或覆盖序列化程序的to_representation方法。这是一个例子:Can to_representation() in Django Rest Framework access the normal fields

第二个可能更方便。