Django rest框架外键约束失败创建模型

时间:2015-10-13 12:50:32

标签: python django django-rest-framework

我在Django Rest Framework设置中有以下内容:

models.py:

ViewImagesViewModel

serializers.py:

class Sku(BaseModel):
    sku_code = models.CharField(max_length=18, primary_key=True)
    supplier_id = models.PositiveIntegerField(db_index=True)
    soh = models.PositiveIntegerField(default=0)
    reserved = models.PositiveIntegerField(default=0)
    broken = models.PositiveIntegerField(default=0)
    unallocated = models.PositiveIntegerField(default=0)
    reorder = models.PositiveIntegerField(default=0)

class Reservation(BaseModel):
    sku = models.ForeignKey(Sku, db_column='sku_code')
    order_id = models.PositiveIntegerField(db_index=True)

views.py:

class SkuSerializer(serializers.ModelSerializer):
    class Meta:
        model = Sku
        fields = (
            'sku_code',
            'supplier_id',
            'soh',
            'reserved',
            'broken',
            'unallocated',
            'reorder',
            'created_at',
            'modified_at',
        )


class ReservationSerializer(serializers.ModelSerializer):
    sku = SkuSerializer(read_only=True)

    class Meta:
        model = Reservation
        fields = (
            'id',
            'order_id',
            'sku',
            'created_at',
            'modified_at'
        )

现在当我发布链接到上面的ReservationList.post视图的网址时,我收到错误:class ReservationList(mixins.CreateModelMixin, generics.GenericAPIView): queryset = Reservation.objects.all() serializer_class = ReservationSerializer def post(self, request, *args, **kwargs): sku = get_object_or_404(Sku, sku_code=request.data['sku_code']) request.data['sku'] = sku return self.create(request, *args, **kwargs)

它似乎绕过了序列化程序验证并在数据库层上失败了。由于某种原因,它不接受传入的SKU。

我在这里做错了什么?我试图在http://www.django-rest-framework.org/api-guide/relations/#nested-relationships上关注示例,但这似乎与IntegrityError: (1048, "Column 'sku_code' cannot be null")分解。我无法判断我的模型或序列化器的设置方式是否有问题。

1 个答案:

答案 0 :(得分:3)

您已将sku字段设置为read only,这就是您发布时序列化程序忽略它的原因。

来自relevant documentation

  

只读字段包含在API输出中,但不应包含在API输出中   在创建或更新操作期间包含在输入中。任何   'read_only'字段错误地包含在序列化程序中   输入将被忽略。