Django Post_Save() Signal Implementation

Django post_save() signal implementation

If you really want to use signals to achieve this, here's briefly how,

from django.db.models.signals import post_save
from django.dispatch import receiver

class TransactionDetail(models.Model):
product = models.ForeignKey(Product)

# method for updating
@receiver(post_save, sender=TransactionDetail, dispatch_uid="update_stock_count")
def update_stock(sender, instance, **kwargs):
instance.product.stock -= instance.amount
instance.product.save()

Testing a django `post_save` signal that includes function calls that occur after db transaction is committed

django.test.TestCase does not support transactions (there is a performance penalty with committing a database transaction and cleaning after test). As per https://docs.djangoproject.com/en/4.0/topics/testing/tools/#django.test.TestCase

  • Wraps the tests within two nested atomic() blocks: one for the whole class and one for each test. Therefore, if you want to test some specific database transaction behavior, use TransactionTestCase.

You should use TransactionTestCase
https://docs.djangoproject.com/en/4.0/topics/testing/tools/#django.test.TransactionTestCase



Related Topics



Leave a reply



Submit