Home > Mobile >  Django post_save won't add to ManyToMany Field
Django post_save won't add to ManyToMany Field

Time:08-19

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?

CodePudding user response:

Saving the instance in the post_save will give you an infinite loop and break.

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)

CodePudding user response:

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()
  • Related