我正在尝试在任何地点附近发送活动。 我接受了这个序列化程序的输入。
class LatLongCateSerializer(serializers.Serializer):
category_id = serializers.IntegerField()
latitude = serializers.DecimalField(max_digits=30,decimal_places=15)
longitude = serializers.DecimalField(max_digits=30,decimal_places=15)
distance = serializers.IntegerField()
然后我尝试从这个帖子视图中获取继承自django rest框架的APIView的事件,如下所示:
class NearbyEvents(APIView):
serializer_class = LatLongCateSerializer
def get_serializer_class(self):
return self.serializer_class
def get_event_serializer(self):
return EventSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
point = Point(float(request.data['latitude']), float(request.data['longitude']))
events = Event.objects.filter(location_point__distance_lte=(point, D(km=int(request.data['distance']))))
if events.exists():
event_serializer = self.get_event_serializer()
ev = event_serializer(data=events)
if ev.is_valid():
return Response(ev.data, status=status.HTTP_200_OK)
else:
print ev.errors
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
我的事件序列化程序继承自GeoFeatureModelSerializer
from rest_framework_gis.serializers import GeoFeatureModelSerializer
class EventSerializer(GeoFeatureModelSerializer):
class Meta:
model = Event
geo_field = 'location_point'
我得到的错误:
{u'non_field_errors': [u'Invalid data. Expected a dictionary, but got GeoQuerySet.']}
我的活动模特:
from location_field.models.spatial import LocationField
class BaseProduct(TimeStamp):
title = models.CharField(_('Title'), max_length=255)
desc = models.TextField(_('Description'), null=True, blank=True)
nearby_metro = models.CharField(_("Neraby Metro Station"), max_length=100, null=True, blank=True)
location_point = LocationField(based_fields=[address], zoom=7, default='Point(1.0 1.0)')
latitude = models.DecimalField(max_digits=30,decimal_places=15,null=True, blank=True)
longitude = models.DecimalField(max_digits=30,decimal_places=15,null=True, blank=True)
请指导我解决问题。
答案 0 :(得分:1)
问题是内在的“序列化”过程。实际上它是使用反序列化模式实现的,当然不起作用。看起来应该是这样的:
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
point = Point(float(request.data['latitude']), float(request.data['longitude']))
events = Event.objects.filter(location_point__distance_lte=(point, D(km=int(request.data['distance']))))
if events.exists():
event_serializer = self.get_event_serializer()
ev = event_serializer(events, many=True)
return Response(ev.data, status=status.HTTP_200_OK)
return Response(status=status.HTTP_400_BAD_REQUEST)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
答案 1 :(得分:0)
ev = event_serializer(data=events)
应该是
ev = event_serializer(data=events,many=True)