如何创建一个对象,然后在Django Rest Framework

时间:2017-08-25 16:45:24

标签: django django-rest-framework

我正在尝试使用Django REST Framework的ModelViewSetModelSerializer创建一个新对象,并将现有对象与其ForeignKey字段相关联。我有两个具有一对多关系的模型,基本上是制造商和产品。制造商已经存在于数据库中,我正在尝试单独添加产品并同时分配它的制造商。当我这样做时,DRF给了我这个错误:

  

“non_field_errors”:[       “数据无效。预计字典,但得到产品。”   ]

以下是我的模型的样子(我试图取出不需要的代码来保持它的小)。创建产品时,manufacturer字段是一个整数,表示其相关对象的ID。正如您在我的视图中所看到的,我查询Manufacturer对象,设置它然后继续让DRF创建对象。如果有人可以告诉我哪里出错了,我会非常感激!

models.py

class Manufacturer(models.Model):
    name = models.CharField(max_length=64)
    state = models.CharField(max_length=2)

class Product(models.Model):
    manufacturer = models.ForeignKey(Manufacturer, related_name="products")
    name = models.CharField(max_length=64)
    sku = models.CharField(max_length=12)

views.py

class ProductViewSet(view sets.ModelViewSet):
    model = Product
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        # get logged in user's manufacturer
        return Product.objects.filter(manufacturer=manufacturer)

    def create(self, request, *args, **kwargs):
        if "manufacturer" in request.data:
            manufacturer = Manufacturer.objects.get(pk=request.data["manufacturer"])
            request.data["manufacturer"] = manufacturer

        return super(ProductViewSet, self).create(request, *args, **kwargs)

serializers.py

class ManufacturerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Manufacturer
        fields = ("id", "name", "state",)
        read_only_fields = ("id",)

class ProductSerializer(serializers.ModelSerializer):
    manufacturer = ManufacturerSerializer()

    class Meta:
        model = Product
        fields = ("id", "manufacturer", "name",)
        read_only_fields = ("id",)

1 个答案:

答案 0 :(得分:1)

您必须设置manufacturer_id密钥。

将序列化程序更改为:

class ProductSerializer(serializers.ModelSerializer):
    manufacturer = ManufacturerSerializer(read_only=True)
    manufacturer_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Product
        fields = ("id", "manufacturer", "name",)
        read_only_fields = ("id",)

将您的创建方法更改为:

def create(self, request, *args, **kwargs):
    if "manufacturer" in request.data:
        request.data["manufacturer_id"] = request.data['manufacturer']

    return super(ProductViewSet, self).create(request, *args, **kwargs)