Django charfield构成默认值 [英] Django charfield compose default value

查看:648
本文介绍了Django charfield构成默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将一个组合的默认值添加到一个字段?

How can I add a composed default value to a charfield?

示例

class Myclass(xxx ):

class Myclass(xxx):

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

可以吗?

推荐答案

为此,您可以覆盖模型上的保存方法。

To do so, you override the save method on your model.

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()

有些东西你需要注意,比如把代码写成一个空白字段,但是你会得到这个想法。

There is stuff you need to take care, like making the code a blank field, but you get the idea.

这篇关于Django charfield构成默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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