问题
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.
class UserProfile(models.Model): user = models.OneToOneField(User, unique=True, null=True, related_name="profile")
Create firstly model User and after that UserProfile model with two posts.
- 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