在Django中执行模型创建代码

时间:2011-11-17 16:29:12

标签: django django-models

我想在Django模型首次创建时执行一些代码。之后,只要保存,我想执行其他一些代码。通过覆盖save()方法可以轻松完成第二个任务。 我该如何完成第一项任务?

3 个答案:

答案 0 :(得分:26)

使用receiver装饰器扩展sdolananswer

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

答案 1 :(得分:11)

您可以使用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)

答案 2 :(得分:0)

field.default

字段的默认值。这可以是一个值或一个可调用对象。如果可调用,则每次创建新对象时都会调用它。

所以,我们可以使用任何可调用的字段来做我们想做的事情,是吧? ;-)