首页 > 解决方案 > how to get distance in drf api response?

问题描述

I have exactly the same problem as this SO question (Sorry for the link and not writing the whole content again.)

Also, I have already implemented the solution given for the same problem.

but I am not getting distance in API response. I haven't added distance in serializer fields so definitely, it won't show up in response. But when I add it to fields I get the following error.

Field name distance is not valid for model Address.

I also tried to write a serializer method field but was not sure how to pass the location received in query params to the serializer for comparison.

So the question is how the distance is supposed to send in API response?

标签: djangodjango-rest-frameworkgeodjango

解决方案


如果您使用该distance字段注释您的查询集,您还需要编辑您的序列化程序以包含该特定字段:

class AddressSerializer(serializers.ModelSerializer):
    #...
    distance = serializers.DecimalField(max_digits=10, decimal_places=2)
    #...

    class Meta:
        model = Address
        fields = ('distance', ) #add other fields you need

推荐阅读