嵌套tastypie UserProfileResource和UserResource,列\“user_id \”中的空值违反非空限制 [英] Nesting tastypie UserProfileResource and UserResource, null value in column \"user_id\" violates not-null constraint

查看:287
本文介绍了嵌套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']

我正在尝试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/

但是得到以下错误:

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


推荐答案

在POST请求上,tastypie是尝试创建来自所请求数据的新对象,但在请求的配置文件对象数据中,您不传递用户参数。 UserProfile模型对于用户而言不允许为空,服务器引发异常。

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.

我将给您一些解决方案,因为我不知道您的模型究竟是什么。 / p>

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)

首先创建模型用户,之后创建UserProfile模型

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

这篇关于嵌套tastypie UserProfileResource和UserResource,列\“user_id \”中的空值违反非空限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆