[Django]-Django Tastypie – automatically pick up current user resource


The current validated answer is sub-optimal since it results in 2 SQL queries.

You should rather modify your queryset as follow:

queryset = Question.objects.select_related('owner').all()

This way the ‘owner’ data is joined in one single SQL query.


Ah… got it figured out now. What worked:

class QuestionResource(ModelResource):
    owner = fields.ForeignKey(UserResource, 'owner')
    class Meta:
        queryset = Question.objects.all()
        allowed_methods = ['get','post']
        fields = ['title','type']
        resource_name = 'question'
        include_resource_uri = True
        serializer = PrettyJSONSerializer()
        authentication = BasicAuthentication()
        authorization = Authorization()

    def hydrate(self, bundle, request=None):
        bundle.obj.owner = User.objects.get(pk = bundle.request.user.id)
        return bundle 

I needed bundle.request.user.id rather than just request.user.id. Perhaps the other question I was looking at referred to an older version of TastyPie – seems older versions didn’t have request accessible in the bundle?

Leave a comment