[Django]-How to populate a model field via django signals with post_save?

7👍

✅

I think you really want to do this:

@receiver(post_save, sender=Ticket)
def ticket_designation(sender, instance, created, **kwargs):
    if created:
        designation = "#" + "000" + str(instance.id)
        Ticket.filter(pk=instance.pk).update(designation=designation)
        print("Ticket" + instance.designation + " was created.")

Explanation:

why use if created: designation is only created once when the new Ticket is created. It’s not updated every time you save the same object.

why use Ticket.objects.filter(..).update(..) : we cannot do instance.save() as it’ll then call this post_save again and recursion occurs. .update on queryset does not call signals so we’re safe.


If you want to use instance.save you might want to look at how to prevent post_save recursion in django.

Leave a comment