class ProjectResource(ModelResource):
class Meta(object):
queryset = models.Projects.objects.all()
resource_name = 'projects'
list_allowed_methods = ['get', 'post', 'put']
always_return_data = True
default_format = 'application/json'
user = auth.ValidateUser()
def get_list(self, request, **kwargs):
user_projects = super(ProjectResource, self).get_list(request, **kwargs)
result = json.dumps(user_projects.content)
return http.HttpResponse(result,
content_type='application/json', status=200)
这是我的tastypie资源。如果我从auth.ValidateUser()找到一个用户,我只需要回复项目表中的关联项目。如果不是,我想显示错误字典,表示没有分配项目。我无法为get_list添加过滤器。
我可以使用get_object_list但是如果我想回复自定义响应,例如错误dict({'error':'No user mapped。'}),则会抛出错误AttributeError: "'dict' object has no attribute 'filter'"
这里非常感谢任何帮助。
答案 0 :(得分:1)
您可以在get_object_list
中进行过滤,然后在get_list
中进行过滤,如果查询集为空,则返回您的词典。
或者,您可以在get_object_list
中执行以下操作:
from tastypie.exceptions import ImmediateHttpResponse
response = http.HttpResponse(json.dumps({'error': 'No user mapped.'}),
content_type='application/json', status=400)
raise ImmediateHttpResponse(response=response)