2012-08-06 54 views
1

看到重复的键错误我有一个用户配置类:更新与/嵌套资源(用户/用户配置文件) - 上PATCH

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    bio = models.CharField(max_length=180, null=True) 

链接到User类。

AUTH_PROFILE_MODULE = 'plantvillage.userprofile' 

我想通过tastypie提供一个API,让用户的细节和USERPROFILE细节可以在同一时间进行管理。如果可能,我想而不是公开两个接口(一个用于用户,另一个用于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 [email protected]: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 

我可以做什么样的变化,使这项工作?

回答

2

可以摆脱UserResource完全从要公开这样的User模型添加字段:

username = fields.CharField(attribute = 'user__username') 

这不仅从User模型GET请求的情况下发送适当的数据,但也照顾更新。