我有一个UserProfile类:
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.CharField(max_length=180, null=True)
它与User类相关联。
AUTH_PROFILE_MODULE = 'plantvillage.userprofile'
我想通过tastypie提供一个API,以便可以同时管理用户详细信息和用户配置文件详细信息。如果可能的话,我想不公开两个接口(一个用于用户,一个用于userprofiles)。
我设置了我的资源:
class ProfileResource(ModelResource):
class Meta:
queryset = UserProfile.objects.all()
resource_name = 'profile'
authentication = ApiKeyAuthentication()
authorization = DjangoAuthorization()
allowed_methods = ['get', 'put', 'patch']
class UserResource(ModelResource):
profile = fields.ToOneField(ProfileResource, 'userprofile', full=True)
class Meta:
queryset = User.objects.filter(is_staff=False)
resource_name = 'usr'
authentication = ApiKeyAuthentication()
authorization = DjangoAuthorization()
excludes = ['password', 'is_active', 'is_staff']
然而,更新
curl --dump-header - -H "Authorization: ApiKey abc6@abc.com:1432ece6a1f34fae24a77315b5c924f756f13807" -H "Content-Type: application/json" -X PATCH --data '{"profile":{"bio":"aquarium"}}' "http://127.0.0.1:8000/api/usr/25/"
导致此错误:
"error_message": "duplicate key value violates unique constraint \"plantvillage_userprofile_user_id_key\"\n", "traceback": "Traceback (most recent call last):\n\n File \"/usr/local/lib/python2.6/dist-packages/django_tastypie-0.9.12_alpha-py2.6.egg/tastypie/resources.py\", line 196, in wrapper\n
我可以做些什么改变来使这项工作?
答案 0 :(得分:2)
您可以完全摆脱UserResource
并添加您想要公开的User
模型中的字段:
username = fields.CharField( attribute = 'user__username' )
这不仅会在GET请求的情况下从User
模型发送正确的数据,还会处理更新。