[Fixed]-Execute code on model creation in Django

16๐Ÿ‘

โœ…

You can use django signalsโ€˜ post_save:

# models.py

from django.db.models import signals

class MyModel(models.Model):
    pass

def my_model_post_save(sender, instance, created, *args, **kwargs):
    """Argument explanation:

       sender - The model class. (MyModel)
       instance - The actual instance being saved.
       created - Boolean; True if a new record was created.

       *args, **kwargs - Capture the unneeded `raw` and `using`(1.3) arguments.
    """
    if created:
        # your code goes here


# django 1.3+
from django.dispatch import dispatcher
dispatcher.connect(my_model_post_save, signal=signals.post_save, sender=MyModel)

# django <1.3
from django.db.models.signals import post_save
post_save.connect(my_model_post_save, sender=MyModel)
๐Ÿ‘คSam Dolan

38๐Ÿ‘

Extending sdolanโ€˜s answer by using receiver decorator:

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

class MyModel(models.Model):
    pass

@receiver(models.signals.post_save, sender=MyModel)
def execute_after_save(sender, instance, created, *args, **kwargs):
    if created:
        # code
๐Ÿ‘คTomas Tomecek

0๐Ÿ‘

field.default

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

So, we can use any field callable to do what we want on creation, huh? ๐Ÿ˜‰

๐Ÿ‘คMechanic

Leave a comment