我有以下代码似乎工作正常,除了request
中的kwargs
和get_object_list
为空
class Target(object):
def __init__(self, x=None, y=None):
self.id = 1 #Since tastypie needs an id
self.x = x
self.y = y
class TargetResource(Resource):
x = fields.IntegerField(attribute='x')
y = fields.IntegerField(attribute='y')
def get_object_list(self, request=None, **kwargs):
targets = []
print 'Got Request %s kwargs %s' %(request, kwargs)
target = self.obj_get(request, **kwargs)
targets.append(target)
return targets
def obj_get(self, request=None, **kwargs):
#Do something that requires the request and kwargs
#Return an instance of Target
def detail_uri_kwargs(self, bundle_or_obj):
kwargs = {}
if isinstance(bundle_or_obj, Bundle):
kwargs['pk'] = bundle_or_obj.obj.id
else:
kwargs['pk'] = bundle_or_obj.id
return kwargs
def obj_get_list(self, request=None, **kwargs):
# Filtering disabled for brevity...
return self.get_object_list(request)
class Meta:
resource_name = 'target'
allowed_methods = ['get']
object_class = Target
authorization = DjangoAuthorization()
authentication = MultiAuthentication(BasicAuthentication(), SessionAuthentication())
答案 0 :(得分:3)
obj_get_list
由get_list
(tastypie/resources.py)调用
如果您查看get_list
代码:
def get_list(self, request, **kwargs):
base_bundle = self.build_bundle(request=request)
objects = self.obj_get_list(bundle=base_bundle, *self.remove_api_resource_names(kwargs))
...
您可以看到请求以捆绑形式传递到obj_get_list
。
因此,您应该实现以下obj_get_list
来获取请求:
def obj_get_list(self, request=None, **kwargs):
return self.get_object_list(kwargs['bundle'].request)
答案 1 :(得分:1)
**kwargs
未填充,因为普通get_object_list()
不接受它们。来自tastypie/resources.py:def get_object_list(self, request):
至于request
,例如:
def get_object_list(self, request):
if request is None:
import pdb
pdb.set_trace()
# the rest of your get_object_list() code
应该让你进入调试器,让你弄清楚哪些代码没有传递请求。