添加到“构造函数”的django模型 [英] Adding to the "constructor" of a django model
问题描述
更新。其他详细信息:意图是初始化该模型的实例所代表的状态机。这个状态机由一个导入的库提供,它的内部状态由我的django模型持久化。这个想法是,每当模型加载时,状态机将自动用模型的数据初始化。
覆盖 __ init __
可能会工作,但这是坏主意,它不是Django的方式。
在Django中正确的方法是使用信号。
在这种情况下,您感兴趣的是 pre_init
和 post_init
。
django.db.models.signals.pre_init
每当你实例化一个Django
模型时,这个信号都是在模型的$ code> __ init __()
方法的开头发送的。 p>
django。 db.models.signals.post_init
喜欢
pre_init
,但当$__ init __()
:方法完成
所以你的代码应该是这样的东西,例如:
从django.db导入模型
m django.db.models.signals import post_init
class MyModel(models.Model):
#正常模型定义...
def extraInitForMyModel(** kwargs)
instance = kwargs.get('instance')
do_whatever_you_need_with(instance)
post_init.connect(extraInitForMyModel,MyModel)
您还可以将信号连接到Django的预定义模型。
I want to do an extra initalization whenever instances of a specific django model are created. I know that overriding __init__ can lead to trouble. What other alternatives should I consider?
Update. Additional details: The intent is to initialize a state-machine that the instances of that model represent. This state-machine is provided by an imported library, and it's inner state is persisted by my django-model. The idea is that whenever the model is loaded, the state machine would be automatically initialized with the model's data.
Overriding __init__
might work, but it's bad idea and it's not the Django way.
The proper way of doing it in Django is using signals.
The ones that are of interest to you in this case are pre_init
and post_init
.
django.db.models.signals.pre_init
Whenever you instantiate a Django model, this signal is sent at the beginning of the model’s
__init__()
method.
django.db.models.signals.post_init
Like
pre_init
, but this one is sent when the__init__()
: method finishes
So your code should be something like
from django.db import models
from django.db.models.signals import post_init
class MyModel(models.Model):
# normal model definition...
def extraInitForMyModel(**kwargs):
instance = kwargs.get('instance')
do_whatever_you_need_with(instance)
post_init.connect(extraInitForMyModel, MyModel)
You can as well connect signals to Django's predefined models.
这篇关于添加到“构造函数”的django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!