【发布时间】:2015-03-16 11:15:57
【问题描述】:
我有以下 OneToOne 映射到 User 表的 CustomerProfile 模型:
class CustomerProfile(models.Model):
'''Profile details of the customers. All extra details are mentioned
here.'''
user = models.OneToOneField(User, related_name='profile')
phone = models.CharField(max_length=200, null=True, blank=True)
class Meta:
app_label = 'testapp'
def __unicode__(self):
return unicode(self.user)
我使用 Tastpye 框架创建了 REST API,并带有以下 resource.py 来获取用户及其个人资料详细信息
class UserResource(ModelResource):
'''Fetch user details'''
class Meta:
queryset = User.objects.all()
resource_name = 'user'
include_resource_uri = False
allowed_methods = ['get']
excludes = ['password','last_login','is_superuser','is_staff','date_joined']
filtering = {
'id': ['exact'],
'username': ['exact']
}
class CustomerProfileResource(ModelResource):
'''Fetch customer details and all coupons'''
class Meta:
queryset = CustomerProfile.objects.all()
resource_name = 'customer'
include_resource_uri = False
allowed_methods = ['get']
现在我想要的是使用单个 API 调用 (/user) 的用户也能够获取其个人资料详细信息。谁能告诉我该怎么做。
仅供参考,我在 UserResource 类中添加了以下代码来实现这一点:
profile = fields.ToManyField('coin.api.CustomerProfileResource', 'profile', null=True, full=True)
但我收到此错误:
{"error_message": "'CustomerProfile' object has no attribute 'all'", "traceback": "Traceback (most recent call last):\n\n File \"/home/rajeev/projects/bitbucket/coin/env/local/lib/python2.7/site-packages/tastypie/resources.py\", line 195, in wrapper\n response = callback(request, *args, **kwargs)
我已经浏览了很多来实现这一点,但还没有找到任何可以实现所需输出的东西。请提出一些解决方案。
【问题讨论】: