Django docs仅列出了覆盖save()
和delete()
的示例.但是,我想为我的模型only when they are created定义一些额外的处理.对于任何熟悉Rails的人来说,这相当于创建了一个:before_create
型过滤.这个是可能的吗?
Django docs仅列出了覆盖save()
和delete()
的示例.但是,我想为我的模型only when they are created定义一些额外的处理.对于任何熟悉Rails的人来说,这相当于创建了一个:before_create
型过滤.这个是可能的吗?
重写__init__()
将导致在实例化对象的python表示时执行代码.我不知道rails,但:before_created
过滤器听起来像是在数据库中创建对象时要执行的代码.如果要在数据库中创建新对象时执行代码,应重写save()
,判断对象是否具有pk
属性.代码如下所示:
def save(self, *args, **kwargs):
if not self.pk:
# This code only happens if the objects is
# not in the database yet. Otherwise it would
# have pk
super(MyModel, self).save(*args, **kwargs)