-1

This is my model:

class Stock_Total(models.Model):
    purchases   = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasetotal')
    stockitem   = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') 
    gst_rate    = models.DecimalField(max_digits=4,decimal_places=2,default=5)

@receiver(pre_save, sender=Stock_Total)
def update_gst_rate(sender, instance, *args, **kwargs):
    instance.gst_rate = instance.stockitem.gst_rate

@receiver(post_save, sender=Purchase)
def trigger_gst(sender, instance, *args, **kwargs):
    instance.purchasetotal.save()

"Purchase" and "Stockdata" are other model which I have created...I just want to save the Stock_Total model whenever the Purchase model is saved i.e. when I click on save on Purchase model the Stock_Total model will automatically be updated along with the purchase model...

Do anyone have any idea?

Niladry Kar
  • 1,163
  • 4
  • 20
  • 50
  • `instance.purchasetotal` is a one-to-many relation, it can refer to zero, one, or more items. But calling `.save()` on it has no sense, since you basically would ask the database to "update thie field in the table with the values already in the table". – Willem Van Onsem Nov 02 '18 at 08:02
  • Is there any other way to do this??? – Niladry Kar Nov 02 '18 at 09:39

1 Answers1

0

I just want to save the Stock_Total model whenever the Purchase model is saved

You don't need signals for that. See below; names have been changed to protect PEP 8.

class StockTotal(models.Model):
    purchases = models.ForeignKey(
        Purchase,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='stock_totals',
    )
    # ...


class Purchase(models.Model):
    # ...

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        for total in self.stock_totals.all():
            # Do whatever updates you want here
            total.save()

Note that the total values in here are going to be the database values; they'll be freshly retrieved by the [related_name].all() call.

It's not really clear to me what you're trying to do. If you want to edit the values on the StockTotal instances when associated Purchase objects are saved, this will work; if you just want to make sure the m2m relations are maintained, you don't need to do anything for that.

If this doesn't help, please do edit your question to clarify.

kungphu
  • 4,592
  • 3
  • 28
  • 37