我创建了一个BaseResource
class BaseResource(ModelResource):
def wrap_view(self, view):
@csrf_exempt
def wrapper(request, *args, **kwargs):
try:
callback = getattr(self, view)
return callback(request, *args, **kwargs)
except IntegrityError, e:
return HttpResponse(e, status=300,
reason='Internal Server error')
return wrapper
class Meta:
allowed_methods = ['get', 'post', 'put']
list_allowed_methods = ['get', 'post', 'put']
detail_allowed_methods = ['get', 'post', 'put']
include_resource_uri = False
default_format = 'application/json'
always_return_data = True
throttle = BaseThrottle(throttle_at=3, timeframe=10,
expiration=1)
authentication = MultiAuthentication(SessionAuthentication(),
ApiKeyAuthentication())
authorization = Authorization()
serializer = urlencodeSerializer()
有我的资源:
class UserResource(BaseResource):
groups = fields.ToManyFields('GroupResource', 'group')
class Meta:
queryset = User.objects.all()
resource_name = 'user'
excludes = ['password']
authorization = Authorization()
allowed_methods = ['get', 'post', 'put']
filtering = {'username': ALL, 'email': ALL}
class GroupResource(BaseResource):
user = fields.ForeignKey(UserResource, 'user')
permissions = fields.ToManyFields('PermissionResource','permissions_set', related_name='permission')
class Meta:
queryset = Group.objects.all()
allowed_methods = ['get', 'post', 'put']
resource_name = 'group'
class PermissionResource(BaseResource):
group = fields.ToOneField('GroupResource', 'group_set')
class Meta:
queryset = Permission.objects.all()
allowed_methods = ['get']
我试图为扩展BaseResource的用户创建一个资源,但是当我建立关系时,我得到以下错误:
groups = fields.ToManyFields('GroupResource', 'group')
AttributeError: 'module' object has no attribute 'ToManyFields'
我已经搜索过,但是我找不到任何能让我感到满意的东西。 有线索吗?我做错了什么?一切都是受欢迎的。谢谢!
答案 0 :(得分:3)
AttributeError
告诉你到底出了什么问题:
对于您的群组资源:
class GroupResource(BaseResource):
user = fields.ForeignKey(UserResource, 'user')
permissions = fields.ToManyFields('PermissionResource','permissions_set', related_name='permission')
您正在使用ToManyFields
,但您尚未在GroupResource
中定义,这意味着它必须来自超级类,从BaseResource开始(未定义)和ModelResource,这里没有粘贴。
虽然您可以调试并查找实际定义此方法的位置,但您尝试使用的字段似乎不在Django documentation中,而是在TastyPie文档中。
你似乎有一个错字。 Django-TastyPie字段实际上名为ToManyField
。