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

StackOverflow https://stackoverflow.com/questions/14974916

  •  10-03-2022
  •  | 
  •  

Domanda

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\
È stato utile?

Soluzione

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.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top