Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 10th, 2012  |  syntax: None  |  size: 1.86 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Python TastyPie - Custom manager methods as filters?
  2. class AdvertManager(models.GeoManager):
  3.  
  4.     def within_box(self, x0, y0, x1, y1):
  5.         geometry = Polygon.from_bbox((x0, y0, x1, y1,))
  6.         return self.filter(point__within=geometry)
  7.        
  8. http://127.0.0.1:8000/api/v1/advert/?format=json&box=51.623349,-3.25362,51.514195,-3.4754133
  9.        
  10. def build_filters(self, filters=None):
  11.         if not filters:
  12.             filters = {}
  13.         orm_filters = super(AdvertResource, self).build_filters(filters)
  14.  
  15.         if 'box' in filters:
  16.             points = [float(p.strip()) for p in filters['box'].split(',')]
  17.             orm_filters = {'box': Advert.objects.within_box(*points).all()}
  18.  
  19.         return orm_filters
  20.        
  21. class AdvertResource(ModelResource):
  22.  
  23.     longitude = fields.FloatField(attribute='longitude', default=0.0)
  24.     latitude = fields.FloatField(attribute='latitude', default=0.0)
  25.     author = fields.ForeignKey(UserResource, 'author')
  26.  
  27.     def build_filters(self, filters=None):
  28.         """
  29.         Build additional filters
  30.         """
  31.         if not filters:
  32.             filters = {}
  33.         orm_filters = super(AdvertResource, self).build_filters(filters)
  34.  
  35.         if 'point__within_box' in filters:
  36.             points = filters['point__within_box']
  37.             points = [float(p.strip()) for p in points.split(',')]
  38.             orm_filters['within_box'] = points
  39.  
  40.         return orm_filters
  41.  
  42.     def apply_filters(self, request, applicable_filters):
  43.         """
  44.         Apply the filters
  45.         """
  46.         if 'within_box' in applicable_filters:
  47.             area = applicable_filters.pop('within_box')
  48.             poly = Polygon.from_bbox(area)
  49.             applicable_filters['point__within'] = poly
  50.         return super(AdvertResource, self).apply_filters(request,
  51.                                                         applicable_filters)
  52.        
  53. { 'withinbox' : 'point__within' }