Note that there are some explanatory texts on larger screens.

plurals
  1. POPython TastyPie - Custom manager methods as filters?
    primarykey
    data
    text
    <p>I have a GeoDjango project that has a manager model like this;</p> <pre><code>class AdvertManager(models.GeoManager): def within_box(self, x0, y0, x1, y1): geometry = Polygon.from_bbox((x0, y0, x1, y1,)) return self.filter(point__within=geometry) </code></pre> <p>I'm trying to get my resource model (AdvertResource) to expose the within_box function through a GET parameter, something like;</p> <pre><code>http://127.0.0.1:8000/api/v1/advert/?format=json&amp;box=51.623349,-3.25362,51.514195,-3.4754133 </code></pre> <p>I started to write a <code>build_filters</code> method on the resource model like this;</p> <pre><code>def build_filters(self, filters=None): if not filters: filters = {} orm_filters = super(AdvertResource, self).build_filters(filters) if 'box' in filters: points = [float(p.strip()) for p in filters['box'].split(',')] orm_filters = {'box': Advert.objects.within_box(*points).all()} return orm_filters </code></pre> <p>But this throws an error "Cannot resolve keyword 'box' into field...".</p> <p>Is it possible to expose methods from a custom manager to the api urls?</p> <p><strong>EDIT - I have now solved this with the following solution.</strong></p> <pre><code>class AdvertResource(ModelResource): longitude = fields.FloatField(attribute='longitude', default=0.0) latitude = fields.FloatField(attribute='latitude', default=0.0) author = fields.ForeignKey(UserResource, 'author') def build_filters(self, filters=None): """ Build additional filters """ if not filters: filters = {} orm_filters = super(AdvertResource, self).build_filters(filters) if 'point__within_box' in filters: points = filters['point__within_box'] points = [float(p.strip()) for p in points.split(',')] orm_filters['within_box'] = points return orm_filters def apply_filters(self, request, applicable_filters): """ Apply the filters """ if 'within_box' in applicable_filters: area = applicable_filters.pop('within_box') poly = Polygon.from_bbox(area) applicable_filters['point__within'] = poly return super(AdvertResource, self).apply_filters(request, applicable_filters) </code></pre> <p>This now means that the request <code>http://127.0.0.1:8000/api/v1/advert/?format=json&amp;point__within_box=51.623349,-3.25362,51.514195,-3.4754133</code> now filters all results within the bounding box.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload