好的,这很划算
序列化器:
from rest_framework import serializers
from happytourist.models import PointsInterestData
class PointsInterestSerializer(serializers.ModelSerializer, serializers.Serializer):
distance = serializers.SerializerMethodField(default=None)
def get_distance(self, obj):
distance_view = self.context.get('distance')
return distance_view
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 post(self, request, *args, **kwargs):
user_latitude = request.POST.get('latitude')
user_longtitude = request.POST.get('longtitude')
radius = request.POST.get('radius')
usergeodata = {'user_latitude': user_latitude, 'user_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
def distancecalc(self, request):
user_latitude = self.post(request=self.request)['user_latitude']
user_longtitude = self.post(request=self.request)['user_longtitude']
latitude = self.get_coordinates()['latitude']
longtitude = self.get_coordinates()['latitude']
x = longtitude - user_longtitude
y = latitude - user_latitude
distance = int((x ** 2 + y ** 2) ** (1 / 2))
return distance
def get_serializer_context(self):
distance_result = PointsInterestList.distancecalc(self, request=self.request)
context = super(PointsInterestList, self).get_serializer_context()
context.update({'distance': distance_result})
return context
我需要做的是获取纬度和经度,从模型中获取纬度和经度,计算它们之间的距离。我的问题是将距离转换成新的价值。在视图中,我发布了这两个值。在获取坐标时,我从模型中得到两个值。在distancecalc中,我想计算。