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
You should use
- 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
.
TransactionTestCase
https://docs.djangoproject.com/en/4.0/topics/testing/tools/#django.test.TransactionTestCase
Related Topics
Differencebetween Np.Array() and Np.Asarray()
Setting Up S3 for Logs in Airflow
Python Pandas Dataframe, Is It Pass-By-Value or Pass-By-Reference
How to Upsert Pandas Dataframe to Microsoft SQL Server Table
How to Change a Widget's Font Style Without Knowing the Widget's Font Family/Size
Pip: How to Install a Git Pull Request
Disable or Lock Mouse and Keyboard in Python
Can't Use '\1' Backreference to Capture-Group in a Function Call in Re.Sub() Repr Expression
How to Know/Change Current Directory in Python Shell
What Does Model.Train() Do in Pytorch
Using Only the Db Part of Django
Changing the Options of a Optionmenu When Clicking a Button
What Are All the Dtypes That Pandas Recognizes
Appending to the Same List from Different Processes Using Multiprocessing
Global Dictionaries Don't Need Keyword Global to Modify Them