class TestResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Test.objects.all()
resource_name = 'test'
authorization = Authorization()
authentication = BasicAuthentication()
如何获取实际登录用户创建的Test
个对象?
所有对象:
http:// 127.0.0.1:8000/api/test/?format=json
答案 0 :(得分:0)
假设您要根据当前登录的用户返回资源,可以通过覆盖资源上的apply_authorization_limits
来限制返回的资源。通过覆盖obj_create
来设置POST的当前用户同样容易。
有关示例,请参阅:http://django-tastypie.readthedocs.org/en/latest/cookbook.html#creating-per-user-resources。
class TestResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Test.objects.all()
resource_name = 'test'
authorization = Authorization()
authentication = BasicAuthentication()
def obj_create(self, bundle, **kwargs):
return super(TestResource, self).obj_create(bundle,
user=bundle.request.user)
def apply_authorization_limits(self, request, object_list):
return object_list.filter(user=request.user)