tastypie API未在JSON结果中显示ForeignKey
我最近开始使用tastypie来为我的手机应用程序开放API。
我使用的是python-2.7和Django-1.1.2
有两件事让我感到困惑:
1:在EntryResource
类中,当调用ForeignKey
时,他们只是直接调用资源和资源名称,但我这样做时却出现了错误信息。
691. assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
Exception Type: AssertionError at /api/v1/activity-stream-item-subject/
Exception Value: ForeignKey(<class 'api.resources.UserResource'>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
2:如果我把EntryResource
改成user = fields.ForeignKey(UserResource, 'user')
,那么就能正常运行,没有错误信息,但我在JSON响应中看不到相关的信息。
api/resources.py
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
filtering = {
'username': ALL,
}
class EntryResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Entry.objects.all()
resource_name = 'entry'
authorization = Authorization()
filtering = {
'user': ALL_WITH_RELATIONS,
'pub_date': ['exact', 'lt', 'lte', 'gte', 'gt'],
}
有没有什么想法?
2 个回答
-2
如果你想在json结果中显示用户的所有字段,你需要设置 full=True
。
user = fields.ForeignKey(UserResource,user,full=True)
7
我不太确定我是否理解你提到的第一个问题,不过关于第二个问题,你需要明确告诉系统你想要获取完整的资源,方法是使用:
user = fields.ForeignKey(UserResource, 'user',full=True)
否则你会得到资源的地址,而不是实际的内容。 (参考链接)
另外,顺便提一下,记得查看一下要求,里面写着:
Django 1.2及以上版本(可能在Django 1.1上也能用)