Skip to content

Instantly share code, notes, and snippets.

@sunny1304
Forked from MacMaru/searchresource_api.py
Created August 22, 2012 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunny1304/3429056 to your computer and use it in GitHub Desktop.
Save sunny1304/3429056 to your computer and use it in GitHub Desktop.
Tastypie (non-model) Resource example with a listfield populated with m2m data
class SimpleOwnerAuthorization(Authorization):
'''
Does what it says: filters objects by their owner (user).
'''
def __init__(self, ownerfilter=None, *args, **kwargs):
self.ownerfilter = ownerfilter # the user field i.e. 'person__user'
def is_authorized(self, request, object=None):
return True # for now
def apply_limits(self, request, object_list):
if request and hasattr(request, 'user') and self.ownerfilter and object_list:
if request.user.is_authenticated():
ownerfilter = {self.ownerfilter: request.user.id}
object_list = object_list.filter(**ownerfilter)
return object_list
class TagResource(ModelResource):
class Meta:
queryset = Tag.objects.all()
filtering = {
"person": ALL_WITH_RELATIONS,
"pk": ['in', 'exact'],
}
authentication = DjangoAuthentication()
authorization = SimpleOwnerAuthorization(ownerfilter='person__user')
def build_filters(self, filters=None):
'''
Overridden to allow filtering (haystack) search results
'''
if filters is None:
filters = {}
orm_filters = super(TagResource, self).build_filters(filters)
if "q" in filters and len(filters["q"].strip())>1:
# query larger than 2 characters
if "models[]" in filters and 'tags' in filters.getlist('models[]'):
orm_filters = {
"pk__in": [i.pk for i in SearchQuerySet().models(Tag).autocomplete(name_autocomplete=filters['q'])]}
else:
orm_filters = {"pk__in":[]}
return orm_filters
class SearchResource(Resource):
'''
A non-model resource for searching and autocompletion
'''
tags = fields.ListField()
class Meta:
resource_name = 'search'
allowed_methods = ['get']
authentication = DjangoAuthentication()
filtering = { "pk": ['in', 'exact'], }
def get_resource_uri(self, bundle_or_obj):
kwargs = {
'resource_name': self._meta.resource_name,
}
if self._meta.api_name is not None:
kwargs['api_name'] = self._meta.api_name
return self._build_reverse_url("api_dispatch_list", kwargs=kwargs)
def dehydrate_tags(self, bundle):
# FIXME: construct resource_uri dynamically here too
return [ {'id':str(obj['pk']), 'resource_uri':'/api/v1/tag/' + str(obj['pk']) + '/' } for obj in bundle.obj['tags'].values('pk')]
def get_object_list(self, request):
return [{
'tags': TagResource().obj_get_list(request),
},]
def obj_get_list(self, request=None, **kwargs):
return self.get_object_list(request)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment