我在这个问题上苦苦挣扎了一段时间。
好的,这是我的序列化器:
from rest_framework import serializers
from happytourist.models import PointsInterestData
class PointsInterestSerializer(serializers.ModelSerializer, serializers.Serializer):
distance = serializers.IntegerField(default=None)
class Meta:
model = PointsInterestData
fields = ('name', 'latitude', 'longtitude', 'distance')
read_only_fields = fields
from rest_framework import generics
from .serializers import PointsInterestSerializer
from happytourist.models import PointsInterestData
class PointsInterestList(generics.ListCreateAPIView, generics.ListAPIView):
serializer_class = PointsInterestSerializer
def get_queryset(self):
queryset = PointsInterestData.objects.all()
return queryset
def create(self, request, *args, **kwargs):
user_latitude = request.POST.get('latitude')
user_longtitude = request.POST.get('longtitude')
radius = request.POST.get('radius')
usergeodata = {'latitude': user_latitude, 'longtitude': user_longtitude, 'radius': radius}
return usergeodata
def get_coordinates(self):
latitude = PointsInterestData.objects.model.latitude
longtitude = PointsInterestData.objects.model.longtitude
geodata = {"latitude": latitude, "longtitude": longtitude}
return geodata
我要做的是根据视图更改序列化器中的距离参数。我需要编写一个函数,该函数的结果将是计算出的距离(我知道该怎么做),并且该结果将被放入序列化器(我不知道该怎么做)
答案 0 :(得分:0)
如果我理解正确,则可以使用 SerializerMethodField
,并且可以通过 self.context
从视图访问数据。
class PointsInterestSerializer(serializers.ModelSerializer):
distance = serializers.SerializerMethodField(method_name='distancecalc')
def distancecalc(self, pid_obj):
# your logic
context_from_view = self.context
return 0 # or 1
答案 1 :(得分:0)
好的,这是我所做的:
视图:
PointsInterestList类(generics.ListCreateAPIView,generics.ListAPIView):
def get_queryset(self):
queryset = PointsInterestData.objects.all()
返回查询集
def distancecalc():
返回4
def get_serializer_context(self):
distance_result = PointsInterestList.distancecalc()
context = super(PointsInterestList,self).get_serializer_context()
context.update({'distance':distance_result})
返回上下文
serializer_class = PointsInterestSerializer
序列化器:
PointsInterestSerializer类(serializers.ModelSerializer,serializers.Serializer): distance = serializers.SerializerMethodField(default = None)
def get_distance(self,obj):
distance_view = self.context.get('distance')
返回distance_view
类Meta:
模型= PointsInterestData
字段=('名称','纬度','经度','距离')
read_only_fields =字段