Django - 覆盖 Model.create() 方法? [英] Django - Overriding the Model.create() method?
问题描述
Django 文档仅列出覆盖 save()
和 delete()
的示例.但是,我想仅在创建模型时为我的模型定义一些额外的处理.对于熟悉 Rails 的人来说,这相当于创建一个 :before_create
过滤器.这可能吗?
The Django docs only list examples for overriding save()
and delete()
. However, I'd like to define some extra processing for my models only when they are created. For anyone familiar with Rails, it would be the equivalent to creating a :before_create
filter. Is this possible?
推荐答案
重写 __init__()
会导致在实例化对象的 Python 表示时执行代码.我不知道 Rails,但是 :before_created
过滤器听起来像是在数据库中创建对象时要执行的代码.如果要在数据库中创建新对象时执行代码,则应覆盖 save()
,检查对象是否具有 pk
属性.代码看起来像这样:
Overriding __init__()
would cause code to be executed whenever the python representation of object is instantiated. I don't know rails, but a :before_created
filter sounds to me like it's code to be executed when the object is created in the database. If you want to execute code when a new object is created in the database, you should override save()
, checking if the object has a pk
attribute or not. The code would look something like this:
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)
这篇关于Django - 覆盖 Model.create() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!