2012-05-29 31 views
1

我需要在tastypie資源中執行過濾器查詢。輸入應該是URL的頭,例如在django/tastypie資源中傳遞請求變量

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

我試過下面

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() 

跟它name 'request' is not defined。如何在ORM上傳遞過濾器?

回答

4

不知道你爲什麼要在UserResource中繼承請求。

我需要做這樣的事情,我能想出的最佳解決方案是覆蓋派遣方法。像這樣

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

嘛,我發現apply_filter非常有用的。 我們可以通過鏈接像

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

代碼

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