【问题标题】:Post data give me IntegrityError Django发布数据给我 IntegrityError Django
【发布时间】:2018-10-07 05:12:22
【问题描述】:

我是 Django 新手,我正在尝试使用 DRF 为文章发布数据键和值:

class ArticalMetaData(models.Model):
    key = models.CharField()
    value = models.CharField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    class Meta:
        unique_together = ("content_type", "object_id", "key")


class MetaDataCreationSerializer(serializers.ModelSerializer):

    def __init__(self, content_object, *args, **kwargs):
        self.content_object = content_object
        super(MetaDataCreationSerializer, self).__init__(*args, **kwargs)

    class Meta:
        model = MetaData
        fields = ('key', 'value','content_object')

这是视图:

    def create(self, request, pk=None):
    Artical = self.get_object()
    if request.method == 'POST':
        serializer = MetaDataCreationSerializer(data=request.data, content_object=Artical)
        if serializer.is_valid():
            metadata = serializer.save()
            metadata.content_object = Articla
            metadata.save()
            serializer = MetaDataSerializer(metadata)
            return Response(serializer.data)

但这给了我这个错误:

Exception Type: IntegrityError
Exception Value:    
null value in column "object_id" violates not-null constraint

【问题讨论】:

  • 您可以包含您发布的数据吗?序列化程序中的 content_object 是什么?您能否包含您实际使用序列化程序的代码部分(视图)?

标签: python django api django-rest-framework


【解决方案1】:

您似乎有一个现有的数据库,其值为object_id 为空。然后您更新了unique_together 字段。所以现有数据与新规则不匹配,即unique_together。 我建议对数据库进行备份,然后将其删除。然后再次运行makemigrations 和迁移命令。

【讨论】:

    【解决方案2】:

    所以错误来自于在您的序列化程序中,您没有在元字段中指定object_id

    默认情况下,django 模型中的所有字段都是必需的,并且不接受空值。

    如果您希望字段为空,您需要为模型中的字段显式设置null=True。但在你的情况下,因为它是唯一约束的一部分,我不认为 null 是正确的值。

    解决方案是在序列化程序的字段中包含object_id

    您可以在发布请求中发送它,但您的序列化程序将忽略它,因为它不在要序列化的字段列表中。

    这就是为什么我要求您包含您发送的 POST 数据。

    【讨论】:

      猜你喜欢
      • 2013-07-25
      • 1970-01-01
      • 2011-08-02
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 2020-01-27
      相关资源
      最近更新 更多