experiENS/avisstage/api.py

45 lines
1.4 KiB
Python
Raw Normal View History

2017-04-16 00:03:04 +02:00
# coding: utf-8
from tastypie.resources import ModelResource
from avisstage.models import Lieu
from django.contrib.gis import geos
class LieuResource(ModelResource):
class Meta:
queryset = Lieu.objects.all()
resource_name = "lieu"
fields = ["nom", "pays", "coord", "type_lieu", "id"]
2017-04-16 00:03:04 +02:00
2017-04-19 01:56:15 +02:00
def build_filters(self, filters=None, **kwargs):
2017-04-16 00:03:04 +02:00
if filters is None:
filters = {}
orm_filters = super(LieuResource, self).build_filters()
if "lng" in filters and "lat" in filters:
lat = float(filters['lat'])
lng = float(filters['lng'])
pt = geos.Point((lng,lat), srid=4326)
self.reference_point = pt
orm_filters['coord__distance_lte'] = (pt, 50)
if "has_stage" in filters:
orm_filters['stages__public'] = True
2017-04-16 00:03:04 +02:00
return orm_filters
def dehydrate(self, bundle):
bundle = super(LieuResource, self).dehydrate(bundle)
obj = bundle.obj
bundle.data['coord'] = {'lat': float(obj.coord.y),
'lng': float(obj.coord.x)}
if "lat" in bundle.request.GET and "lng" in bundle.request.GET:
bundle.data['distance'] = self.reference_point.distance(bundle.obj.coord)
bundle.data["pays_nom"] = obj.get_pays_display()
bundle.data["type_lieu_nom"] = obj.get_type_lieu_display()
2017-04-16 00:03:04 +02:00
return bundle