创建并保存对象IntegrityError django

时间:2018-08-06 18:37:23

标签: django

我从json响应中获取一个对象,并且想在其上使用create方法,以便将其保存在数据库中。

response = requests.get(
            settings.BASE_URL,
            headers=headers,
            params=payload,
        )
        user_info = response.json()

        example_model = ExampleModel.objects.create(api_key=user_info.get('id'))
        example_model.save()

模型是:

class ExampleModel(models.Model):
    """

    """
    user = models.OneToOneField(User)
    example_id = models.CharField(max_length=225, blank=True, null=True)
    api_key = models.CharField(max_length=225, blank=True, null=True, validators=[validate_klean_token_syntax])

跟进是我收到

Exception Type: IntegrityError at /user-information/
Exception Value: (1048, "Column 'user_id' cannot be null")

有人可以帮助我理解为什么会出现此错误,谢谢。

1 个答案:

答案 0 :(得分:3)

您正在尝试将NULL保存到模型中的字段,并且不能为NULL。您在ExampleModel和用户模型中的user字段之间存在关系,并且模型定义不允许该字段为NULL。

要么允许ExampleModel中的用户为NULL,要么不使用OneToOne之类的引用,否则请确保您的get返回用户值。

相关问题