python - 如何通过 django rest api 中的视图更改序列化程序中的参数
问题描述
好的,这是一笔交易
序列化器:
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 我想计算。
解决方案
推荐阅读
- spotfire - Spotfire 交叉表条件格式
- r - 使用 R Inline 和 fortran 进行多维数组操作
- sql-server - 在 SQL 中的 where/have 中求和
- java - 我试图实现一种方法,从给定字符串的集合中找到任何字符的第一个索引
- c++ - 实现转换链而不重复?
- json - 使用 jq 解析和映射 2 个数组
- java - Java中的拖线
- python - Python中for或while块末尾的“else”有什么用?
- r - R:聚合数据,同时使用基础 R 添加新的计数列
- document - 如何使用 models.hdpmodel 获取文档主题 – gensim 中的分层狄利克雷过程