将额外字段添加到序列化器中,而无需添加到模型中

时间:2019-02-24 09:14:20

标签: python django django-rest-framework

我一直在尝试将字段“距离”添加到结果中包含的字段中。但是,该字段不在模型或序列化程序中,我只是想知道返回此类字段的最佳方法是什么?任何帮助是极大的赞赏。谢谢!

视图是:

class PlaceViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows places to be viewed or edited.
    """

    current_lat = 54.52984
    current_lon = -1.5609

    """
    Haversine formula used to sort places by distance (closest first).
    """
    query = "select distinct id, (((acos(sin((" + format(current_lat) + \
            "*pi()/180)) * sin((lat*pi()/180))+cos((" + format(current_lat) + \
            "*pi()/180)) * cos((lat*pi()/180)) * cos(((" + format(current_lon) + \
            " - lon)*pi()/180))))*180/pi())*60*1.1515) AS distance " \
            "from mobileapi_place " \
            "order by distance asc"

    queryset = Place.objects.raw(query)
    serializer_class = PlaceSerializer

下面是序列化器。

class PlaceSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Place
        fields = ('title', 'lat', 'lon', 'featured_image_url', 'created_at')

1 个答案:

答案 0 :(得分:0)

您尝试过SerializerMethodField吗?

应该是这样的。

class PlaceSerializer(serializers.HyperlinkedModelSerializer):
    distance = SerializerMethodField()

    class Meta:
        model = Place
        fields = ('title', 'lat', 'lon', 'distance', 'featured_image_url', 'created_at')

    def get_distance(self, obj):
        return obj.distance