Nesting tastypie UserProfileResource and UserResource, null value in column \“user_id\” violates not-null constraint

十年热恋 提交于 2020-01-05 08:43:17

问题


This is my setup:

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']

I am trying to POST to the user resource:

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/

But get the following error:

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

回答1:


On POST request tastypie is try create new objects from the requested data, but in the requested data for profile object you don't pass parameter for user. UserProfile model does not allow null for user and the server raise an exception.

I will give you a few solutions because i don't know what exactly your models do.

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

  2. Create firstly model User and after that UserProfile model with two posts.

  3. Implement custom method for create the user and user profile in one post.


来源:https://stackoverflow.com/questions/14974916/nesting-tastypie-userprofileresource-and-userresource-null-value-in-column-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!