I'm using signals in models.py but when I make a sum this function does it twice instead of just a sum
models.py:
class Articulo(models.Model):
cod_experto = models.CharField(max_length=999, primary_key=True, blank=True)
nombre = models.CharField(max_length=999, blank=True)
descripcion = models.CharField(max_length=999, blank=True, null=True)
on_delete=models.CASCADE)
stock = models.IntegerField(blank=True, default=0)
total_pedido =models.IntegerField(blank=True, default=0)
class Pedido(models.Model):
especialidad = models.ForeignKey('Especialidad')
articulo = models.ForeignKey('Articulo')
blank=True)
cantidad = models.IntegerField(blank=True) default='pendiente')
def __str__(self):
return '{}'.format(self.especialidad, self.articulo, self.cantidad, self.estado)
def update_total(sender, instance, **kwargs):
instance.articulo.total_pedido += instance.cantidad
instance.articulo.save()
# register the signal
signals.post_save.connect(update_total,sender=Pedido, dispatch_uid="update_stock_count")
views.py
def Cant_ingresar(request, id_pedido, id_especialidad):
especialidad = Especialidad.objects.get(id=id_especialidad)
pedido = Pedido.objects.get(id=id_pedido)
if request.method == 'GET':
form = PedidoEditForm(instance=pedido)
else:
form = PedidoEditForm(request.POST, instance=pedido)
if form.is_valid():
form.save()
"""
pedido.estado = 'pendiente'
pedido.fecha_pedido = datetime.date.today()
pedido.save()
especialidad.estado='pendiente'
especialidad.save()
"""
return HttpResponseRedirect('/solicitar/lista_active/%s/' % id_especialidad)
return render(request, 'form.html', {'form':form, 'pedido':pedido, 'especialidad':especialidad, 'pedido':pedido})
As you can see, I first save the cantidad entered in the def of views.py, then in the model with the signals captured with post_save the amount and is summed with total_pedido of the Articulo model, this without problems, but adds two Times the same amount ie, enter a 3 and this goes to total_pedido as 6.