django将模型字段的默认值设置为self属性 [英] django set default value of a model field to a self attribute

查看:464
本文介绍了django将模型字段的默认值设置为self属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为Fattura的模型,我想将可打印"字段的默认值设置为包含"numero"字段值的字符串.

I have a model called Fattura, and I would like to set the default value of the field "printable" to a string that includes the value of the field "numero".

但是我有一个错误,那就是link_fattura的参数更少,但是如果我添加default = link_fattura(self),我会遇到一个错误,因为未定义self.

But I have the error that link_fattura has less arguments, but if I add default=link_fattura(self) I have an error because self is not defined.

我该如何解决这个问题?

How can I solve this issue?

class Fattura(models.Model):
        def link_fattura(self, *args, **kwargs):
                return u"http://127.0.0.1:8000/fatture/%s/" % (self.numero)
        data = models.DateField()
        numero = models.CharField("Numero", max_length=3)
        fatturaProForma = models.ForeignKey(FatturaProForma)
        printable = models.CharField("Fattura stampabile", max_length=200, default=link_fattura)
        def __unicode__(self):
                return u"%s %s" % (self.data, self.numero)
        class Meta:
                verbose_name_plural = "Fatture"
                ordering = ['data']

推荐答案

您不能使用default参数执行此操作.最好的选择是覆盖save方法:

You can't do this using the default argument. The best bet is to override the save method:

def save(self, *args, **kwargs):
    if not self.id and not self.printable:
        self.printable = self.link_fattura()
    return super(Fattura, self).save(*args, **kwargs)

这篇关于django将模型字段的默认值设置为self属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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