我需要在tastypie资源中执行过滤查询。输入应该是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上传递过滤器?
答案 0 :(得分:5)
不确定为什么要在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)
答案 1 :(得分: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