如何为Django模型字段定义default
,以基于同一实例上另一个字段的值?
我想根据code
时间戳为模型定义created
:
from django.db import models
class LoremIpsum(models.Model):
code = models.CharField(
max_length=100,
default=(
lambda x: "LOREM-{0.created:%Y%m%d-%H%M%S}".format(x)),
)
created = models.DateTimeField(
auto_now_add=True,
)
这不起作用,因为为default
定义的函数没有收到任何参数。
如何定义code
字段的默认值,使其来自该实例的created
字段值?
答案 0 :(得分:1)
使用Django signals,可以通过从模型定义接收the post_init
signal的功能来完成。
from django.db import models
import django.dispatch
class LoremIpsum(models.Model):
code = models.CharField(
max_length=100,
)
created = models.DateTimeField(
auto_now_add=True,
)
@django.dispatch.receiver(models.signals.post_init, sender=LoremIpsum)
def set_default_loremipsum_code(sender, instance, *args, **kwargs):
"""
Set the default value for `code` 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.code:
instance.code = "LOREM-{0.created:%Y%m%d-%H%M%S}".format(instance)
一旦在实例上进行初始化,类就会发送post_init
信号。这样,实例在测试是否设置了非可空字段之前获取code
的值。