Django - 覆盖Model.create()方法? [英] Django - Overriding the Model.create() method?

查看:124
本文介绍了Django - 覆盖Model.create()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django docs 仅列出覆盖 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆