pre_save signal modifies a model field?pre_save signal that changes a field value before saving. What will be the final saved value in the database?from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) @receiver(pre_save, sender=Product) def update_price(sender, instance, **kwargs): if instance.price < 10: instance.price = 10.00 p = Product(name='Pen', price=5.00) p.save() print(Product.objects.get(name='Pen').price)
pre_save runs and what it can change.The pre_save signal runs before the model instance is saved to the database. Modifying the instance's fields in pre_save changes what gets saved. Here, the price is set to 10.00 if it was less than 10 before saving.
post_save signal?post_save signal that prints a message after saving a model, what will be printed when a new instance is created?from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): username = models.CharField(max_length=50) @receiver(post_save, sender=UserProfile) def notify_save(sender, instance, created, **kwargs): if created: print(f"Created user: {instance.username}") else: print(f"Updated user: {instance.username}") u = UserProfile(username='alice') u.save()
created flag in post_save.The post_save signal receives a created boolean that is True when a new instance is created. The signal prints "Created user: alice" when saving a new UserProfile.
pre_save signal to a model?pre_save signal handler for a Django model named Order.@receiver decorator.Option A correctly uses @receiver(pre_save, sender=Order) to connect the signal handler to the Order model's pre_save event.
Option A misuses @pre_save.connect without specifying sender and has wrong syntax.
Option A uses post_save instead of pre_save.
Option A misses the sender argument, so it listens to all models, which is usually incorrect.
post_save signal cause a recursion error?post_save signal cause a recursion error?from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): bio = models.TextField(blank=True) @receiver(post_save, sender=Profile) def update_bio(sender, instance, **kwargs): if not instance.bio: instance.bio = 'Default bio' instance.save() p = Profile() p.save()
post_save signal.Calling instance.save() inside a post_save signal triggers the signal again, causing infinite recursion and eventually a recursion error.
pre_save and post_save signals?pre_save and post_save signals behave in Django.pre_save is triggered before the model instance is saved to the database, allowing modifications to the instance before saving.
post_save runs after the instance is saved, so changes made in post_save do not affect the current save operation.