passing request variables in django/tastypie resources

巧了我就是萌 提交于 2019-12-11 03:44:18

问题


I need to execute filter query inside tastypie resources. the input should be the headers of url for example

new Ext.data.Store({
   proxy: {
     url :'api/users/'
     type: "ajax",
      headers: {
       "Authorization": "1"
    }
   }
 })  

I tried below

from tastypie.authorization import Authorization
from django.contrib.auth.models import User
from tastypie.authentication import BasicAuthentication
from tastypie import fields
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from tastypie.validation import Validation
from userInfo.models import ExProfile

class UserResource(ModelResource,request):
        class Meta:
            queryset = User.objects.filter(id=request.META.get('HTTP_AUTHORIZATION'))
            resource_name = 'user'
            excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
            authorization = Authorization()
            authentication=MyAuthentication()

it is saying name 'request' is not defined. How to pass filters on ORM them?


回答1:


Not sure why are you inheriting request in UserResource.

I needed to do something like this and the best solution I could come up was to overwrite the dispatch method. Like this

class UserResource(ModelResource):
   def dispatch(self, request_type, request, **kwargs):
        self._meta.queryset.filter(id=request.META.get('HTTP_AUTHORIZATION'))
        return super(UserResource, self).dispatch(request_type, request, **kwargs)



回答2:


Well , i found apply_filter very useful. We can pass link like

http://localhost:8000/api/ca/entry/?format=json&userid=a7fc027eaf6d79498c44e1fabc39c0245d7d44fdbbcc9695fd3c4509a3c67009

Code

class ProfileResource(ModelResource):

        class Meta:
             queryset =ExProfile.objects.select_related()
             resource_name = 'entry'
             #authorization = Authorization()
             #authentication = MyAuthentication()
             filtering = {
                 'userid': ALL,
                 'homeAddress': ALL,
                 'email': ALL,
                 'query': ['icontains',],
                 }
             def apply_filters(self, request, applicable_filters):
                    base_object_list = super(ProfileResource, self).apply_filters(request, applicable_filters)

                    query  = request.META.get('HTTP_AUTHORIZATION')
                    if query:
                        qset = (
                            Q(api_key=query)
                            )
                        base_object_list = base_object_list.filter(qset).distinct()

                    return base_object_list


来源:https://stackoverflow.com/questions/10798230/passing-request-variables-in-django-tastypie-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!