gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:52:43 24 4
gpt4 key购买 nike

我有下一个代码:

模型:

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 编写自己的创建方法。

关于python - 使用具有多对多关系的 Post 方法的 Django Rest-Framework 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29331383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com