2013-02-20 69 views
1

这是我的设置:嵌套tastypie UserProfileResource和UserResource,在列空值“user_ID的”违反了非空约束

class UserProfile(models.Model): 
    user = models.OneToOneField(User, unique=True, related_name="profile") 

class UserProfileResource(ModelResource): 
    class Meta: 
     queryset = UserProfile.objects.all() 
     resource_name = 'profile' 
     authorization = Authorization() 

class UserResource(ModelResource): 
    profile = fields.ToOneField(UserProfileResource, attribute='userprofile', related_name='user', full=True, null=True) 
    class Meta: 
     queryset = User.objects.all() 
     resource_name = 'user' 
     authorization = Authorization() 
     list_allowed_methods = ['get', 'post'] 

我试图张贴到用户资源:

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"username":"tata","password":"poooo","profile":{"home_zipcode": "95124"}}' http://192.168.1.103:8000/api/v1/user/ 

但得到以下错误:

"error_message": "null value in column \"user_id\" violates not-null constraint\ 

回答

0

在POST请求tastypie是尝试建立由叔新对象他请求了数据,但在所请求的profile对象数据中,您不会为用户传递参数。 UserProfile模型不允许用户为空,并且服务器引发异常。

我会给你几个解决方案,因为我不知道你的模型究竟做了什么。

  1. class UserProfile(models.Model): user = models.OneToOneField(User, unique=True, null=True, related_name="profile")

  2. 首先创建模型的用户,并有两个职位,用户配置模式之后。

  3. 实现用于在一个帖子中创建用户和用户配置文件的自定义方法。
相关问题