Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code on model creation in Django

I want to execute some code in a Django model when it is first created. After that whenever it is saved I want to execute some other code. The second task can be easily done by overriding the save() method. How can I do the first task?

like image 477
Rohit Agarwal Avatar asked Nov 17 '11 16:11

Rohit Agarwal


People also ask

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

How can create primary key in Django model?

By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field. If you add your own primary key field, the automatic one will not be added.

How do I create a record in Django?

Create a single record with save() or create() To create a single record on a Django model, you just need to make an instance of a model and invoke the save() method on it. Listing 8-1 illustrates the process to create a single record for a model called Store .


2 Answers

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
like image 138
Tomas Tomecek Avatar answered Sep 19 '22 01:09

Tomas Tomecek


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)
like image 36
Sam Dolan Avatar answered Sep 21 '22 01:09

Sam Dolan