I need the products that each user has ordered, like in the "UsuarioSerializer" i was thinking to put a field "productos" which is a list of "ProductoSeralizer", but the model "Usuario" do not have a direct relation with "ProductoSeralizer", so it give me an error when I try that, how can solve this? I need a JSON response like this:
[
{
"id": 1,
"cantidad_de_productos": 12,
"fecha": "2021-03-21T06:26:26.981487Z",
"correo": "user1@email.com",
"password": "pass",
"productos" : [
{},
{}
]
},
{
"id": 2,
"cantidad_de_productos": 0,
"fecha": "2021-03-21T06:26:56.700399Z",
"correo": "user2@email.com",
"password": "pass",
"productos" : [
{},
{}
]
}
]
models.py
class Entidad(models.Model):
fecha = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Usuario(Entidad):
correo = models.EmailField(unique=True)
password = models.CharField(max_length=20)
def __str__(self) -> str:
return self.correo
class Orden(Entidad):
solicitante = models.ForeignKey(Usuario, related_name='ordenes', on_delete=models.CASCADE)
productos = models.ManyToManyField('Producto', through='Detalle')
class Producto(Entidad):
nombre = models.CharField(max_length=20, unique=True)
ordenes = models.ManyToManyField('Orden', through='Detalle')
def __str__(self) -> str:
return self.nombre
class Detalle(Entidad):
cantidad = models.PositiveIntegerField()
orden = models.ForeignKey(Orden, related_name='detalles', on_delete=models.CASCADE)
producto = models.ForeignKey(Producto, related_name='detalles', on_delete=models.CASCADE)
serializers.py
class ProductoSerializer(serializers.ModelSerializer):
class Meta:
model = Producto
fields = '__all__'
class ProductosUsuarioSerializer(serializers.ModelSerializer):
cantidad = models.IntegerField()
class Meta:
model = Producto
fields = '__all__'
class DetalleOrdenSerializer(serializers.ModelSerializer):
class Meta:
model = Detalle
exclude = ['orden']
class OrdenSerializer(serializers.ModelSerializer):
detalles = DetalleOrdenSerializer(many=True)
class Meta:
model = Orden
exclude = ['productos']
def create(self, validated_data):
detalles_data = validated_data.pop('detalles')
orden = Orden.objects.create(**validated_data)
for detalle_data in detalles_data:
Detalle.objects.create(orden=orden, **detalle_data)
return orden
class DetalleSerializer(serializers.ModelSerializer):
class Meta:
model = Detalle
fields = '__all__'
class UsuarioSerializer(serializers.ModelSerializer):
cantidad_de_productos = serializers.IntegerField()
class Meta:
model = Usuario
fields = '__all__'
views.py
class Usuario(ListCreateAPIView):
queryset = Usuario.objects.annotate(cantidad_de_productos=Coalesce(Sum('ordenes__detalles__cantidad'), 0))
serializer_class = UsuarioSerializer