简体   繁体   中英

Django post_save won't add to ManyToMany Field

I've got these models, and I want to fill an instance of Reporte after it gets saved certain data related to the dates. In the post_save it access the sales made between the dates passed and then it adds them to manytomany field in Reporte but I can't save them to a Reporte instance and I don't understand why

class Venta(models.Model):
    repuesto = models.ForeignKey(Repuestos, models.CASCADE)
    cantidad = models.IntegerField()
    fecha_venta = models.DateField()
    total = models.FloatField(null=True, blank=True)

    def __str__(self):
        return f'{self.repuesto} - {self.cantidad} - {self.fecha_venta}'

class Reporte(models.Model):
    fecha_inicio = models.DateField()
    fecha_fin = models.DateField()
    ventas = models.ManyToManyField(Venta, null=True, blank=True)
    estado_de_cuenta = models.FloatField(null=True, blank=True)
    costo_de_inventario = models.FloatField(null=True, blank=True)
    deficit_de_productos = models.CharField(max_length=100, null=True, blank=True)
@receiver(post_save, sender=Reporte)
def guarda_venta(sender, instance, created, **kwargs):
    if created:
        vent = Venta.objects.all()
        ventas_delta = vent.filter(fecha_venta__range=[instance.fecha_inicio, instance.fecha_fin])
        instance.ventas.set(ventas_delta)
        instance.save()

Anyone knows what am I doing wrong?

Instead of.save() you should use.add()

ex:

@receiver(post_save, sender=Reporte)
def guarda_venta(sender, instance, created, **kwargs):
    if created:
        vent = Venta.objects.all()
        ventas_delta = vent.filter(fecha_venta__range=[instance.fecha_inicio, instance.fecha_fin])
        instance.ventas.add(*ventas_delta)

serializers:

class VentasSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ventas
        fields = [<your fields here>,]

class ReporteSerializer(serializers.ModelSerializer): 
    ventas = VentasSerializer(read_only=True, many=True)

    class Meta: 
        model = Reporte 
        fields = ('fecha_inicio', 'fecha_fin','ventas',) 

after using instance.ventas.add() you have to use instance.save(), that is becouse you create the object but you don't save it yet.

@receiver(post_save, sender=Reporte)
def guarda_venta(sender, instance, created, **kwargs):
    if created:
        vent = Venta.objects.all()
        ventas_delta = vent.filter(fecha_venta__range=[instance.fecha_inicio, instance.fecha_fin])
        instance.ventas.add(*ventas_delta)
        instance.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM