使用具有多对多关系的 Post 方法的 Django Rest-Framework 错误

Django Rest-Framework error using Post method with manytomany relationship

我有下一个代码:

型号:

class Producto(models.Model):

    def __unicode__(self):
        return(self.nombre)

    nombre = models.CharField(max_length=50)
    descripcion = models.TextField(max_length=140)
    color = models.CharField(max_length=15)
    talla = models.CharField(max_length=10)
    precio = models.IntegerField()
    cantidad = models.IntegerField()
    create_date = models.DateTimeField("Fecha de Creacion",auto_now=True)

    def precio_display(self):

        return "Gs. "+ format(self.precio, "8,d")

    precio_display.short_description = 'Precio'


class Venta(models.Model):

    def __unicode__(self):
        return "id: {0}, {1:%H:%M - %d/%m/%Y}".format(self.id,  self.fecha)

    fecha = models.DateTimeField(auto_now=True)
    # Relacion muchos a muchos por medio de la tabla Detalle
    productos = models.ManyToManyField('Producto', through="Detalle",  related_name="productos")
    total = models.IntegerField()
    credencial = models.CharField(max_length=200)


class Detalle(models.Model):

    producto = models.ForeignKey(Producto)
    venta = models.ForeignKey(Venta)
    cant = models.IntegerField()**`strong text`**
    precioVenta = models.IntegerField()

    def __unicode__(self):
        return "Se vendio {0} de {1} en la venta {2}".format(self.cantidad,self.producto, self.venta.id)

序列化程序:

class ProductoModelSerializer(ModelSerializer):

    class Meta:
        model = Producto
        fields = ("id", "nombre", "descripcion", "color", "talla",
                  "precio", "cantidad")


class DetalleSerializer(HyperlinkedModelSerializer):

    id = ReadOnlyField(source='producto.id')
    nombre = ReadOnlyField(source='producto.nombre')

    class Meta:
        model = Detalle

        fields = ('id', 'nombre', 'cant', 'precioVenta')


class VentaModelSerializer(ModelSerializer):
    productos = DetalleSerializer(source='detalle_set', many=True)

    class Meta:
        model = Venta
        fields = ("id", "productos", "total", "credencial")

当我使用 Post 方法时,我得到下一个错误:

TypeError at /stock/rest/ventas/
'Detalle' instance expected, got OrderedDict([(u'cant', 25), (u'precioVenta', 25000)])
Request Method: POST
Request URL:    http://127.0.0.1:8000/stock/rest/ventas/
Django Version: 1.7.5
Exception Type: TypeError
Exception Value:    
'Detalle' instance expected, got OrderedDict([(u'cant', 25), (u'precioVenta', 25000)])

我不知道为什么。当我将此方法与使用 angular.js 完成的 Web 前端一起使用时,get 方法可以完美地工作。但是 POST、PATCH 和 PUT 方法得到了同样的错误。

PD:抱歉我的英语不好。

文档说:

If you're supporting writable nested representations you'll need to write .create() or .update() methods that handle saving multiple objects.

http://www.django-rest-framework.org/api-guide/serializers/

因此在这种情况下,您应该为 POST 编写自己的创建方法。