Django CharField 设置默认值

1 投票
3 回答
3499 浏览
提问于 2025-04-16 11:54

我该如何给一个字符字段添加一个组合的默认值呢?

举个例子

class Myclass(xxx):

type = models.ForeignKey(somewhere)
code = models.CharField(default=("current id of MyClass wich is autoincremented + type value"))

这可能吗?

3 个回答

0

你也可以使用 post_save 信号。

from django.db.models import signals

class MyClass(models.Model):
    type = models.ForeignKey(somewhere)
    code = models.CharField(blank=True)

def set_code_post(instance, created, **kwargs):
    instance.code = str(instance.id) + str(instance.type_id)
    instance.save()

signals.post_save.connect(set_code_post, sender=MyClass)

或者,你可以结合使用 pre_save 和 post_save 信号,这样就可以避免调用 save() 两次……

from django.db.models import signals

class MyClass(models.Model):
    type = models.ForeignKey(somewhere)
    code = models.CharField(blank=True)

def set_code_pre(instance, **kwargs):
    if hasattr(instance, 'id'):
        instance.code = str(instance.id) + str(instance.type_id)

def set_code_post(instance, created, **kwargs):
    if created:
        instance.code = str(instance.id) + str(instance.type_id)
        instance.save()

signals.pre_save.connect(set_code_pre, sender=MyClass)
signals.post_save.connect(set_code_post, sender=MyClass)
2

你应该按照Lakshman的建议重写保存方法,不过因为这是默认设置,并且不是blank=False,所以代码会稍微有些不同:

Class MyClass(models.Model):
...
def save(self):
    if not self.id:
        self.code = str(self.id) + str(self.type_id)
    return super(Myclass,self).save())
2

要做到这一点,你需要在你的模型中重写保存方法。

class MyClass(models.Model):
    ...

    def save(self):
        super(Myclass,self).save()
        if not self.code:
            self.code = str(self.id) + str(self.type_id)
            self.save()

还有一些事情需要注意,比如要把代码设置为一个空字段,但你明白这个意思了。

撰写回答