Skip to content

Instantly share code, notes, and snippets.

@MacMaru
Created December 5, 2012 13:22
Show Gist options
  • Save MacMaru/4215467 to your computer and use it in GitHub Desktop.
Save MacMaru/4215467 to your computer and use it in GitHub Desktop.
Stub for Tastypie ManyToMany and passing request user to Django to do custom filtering.
'''
I've received several requests for examples of my pull request for tastypie.
https://github.com/toastdriven/django-tastypie/pull/214
'''
# in your models.py for instance:
class TimeLogManager( models.Manager ):
use_for_related_fields = True
def for_user(self, user):
qs = self.get_query_set()
# user may see activities:
qs = qs.filter(
# - he owns
activity__person__user=user
).distinct()
# select those related fields we already know we need
qs = qs.select_related('activity', 'activity__deliverable')
return qs
# ... field definitions
class TimeLog( UserModel ):
objects = TimeLogManager()
# other fields go here...
# in api/resources.py (or where you define your api) for instance:
class TimeLogResource( NamespacedModelResource ):
# define your fields here...
class Meta:
queryset = TimeLog.objects.none()
resource_name = 'timelog'
pass_request_user_to_django = True
# ... other stuff
# And you need to create an overloaded version of NamespacedModelResource that contains a custom get_object_list that accepts a request parameter:
class NamespacedModelResource( NamespacedModelResource ):
def get_object_list(self, request):
# Our models have a custom manager 'for_user' that returns
# all the objects the current request.user may view.
if request and hasattr(request, 'user'):
return self._meta.queryset.model.objects.for_user(request.user)
else:
return self._meta.queryset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment