2

我需要在美味派资源中执行过滤器查询。例如,输入应该是 url 的标题

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

2 回答 2

5

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)
于 2012-05-29T13:25:22.677 回答
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
于 2012-05-30T07:51:07.487 回答