<p>使用<a href="https://docs.djangoproject.com/en/stable/topics/signals/" rel="noreferrer">Django signals</a>,这可以很早地完成,方法是从模型接收<a href="https://docs.djangoproject.com/en/stable/ref/signals/#post-init" rel="noreferrer">the ^{<cd1>} signal</a>。</p>
<pre class="lang-python prettyprint-override"><code>from django.db import models
import django.dispatch
class LoremIpsum(models.Model):
name = models.CharField(
"Name",
max_length=30,
)
subject_initials = models.CharField(
"Subject Initials",
max_length=5,
)
@django.dispatch.receiver(models.signals.post_init, sender=LoremIpsum)
def set_default_loremipsum_initials(sender, instance, *args, **kwargs):
"""
Set the default value for `subject_initials` on the `instance`.
:param sender: The `LoremIpsum` class that sent the signal.
:param instance: The `LoremIpsum` instance that is being
initialised.
:return: None.
"""
if not instance.subject_initials:
instance.subject_initials = "".join(map(
(lambda x: x[0] if x else ""),
instance.name.split(" ")))
</code></pre>
<p>一旦类对实例完成初始化,它就会发送<code>post_init</code>信号。这样,在测试是否设置了不可为空的字段之前,实例获取<code>name</code>的值。</p>