[Django]-Python TastyPie – Custom manager methods as filters?

4👍

There are a couple of issues with your code above.

First, yes you can expose any custom manager to anything, regardless if you are using it tastypie or not. AdvertManager you defined above can be accessed through Advert.objects only if you have replaced it default manager with your own version.

Second, the way you want to expose tastypie filtering on AdvertResource is orthogonal on how filtering actually works.

All filters are applied as practically ORM filters in the form <field_name>__<filter_name>=<value_or_values>. Since in your example you are using box=<number>,<number>,...,<number> tastypie explodes that into box__exact=... and tries to find box field in AdvertResource and fails as expected.

If your advert has a field called location you could add withinbox as a filter for that field and filter by: location__withinbox=<values>.

If you want to keep your original approach, you would have to parse the box filter yourself from request.GET dictionary and then pass them to your own overridden version of obj_get and obj_get_list in AdvertResource.

Finally, when extending build_filters you are only making a mapping between Tastypie filter and an ORM filter. In your example you are returning objects as a filter; instead simply define it as:

{ 'withinbox' : 'point__within' }

and convert the list of values into Polygon within apply_filters before it is handed off to the actual filter method.

Leave a comment