django set default value of a model field to a self attribute

半城伤御伤魂 提交于 2019-12-24 14:55:47

问题


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".

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']

回答1:


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)



回答2:


Sorry I read you question wrong, that's not possible without javascript because your model hasn't been saved at that stage yet.

You could forecast the url by doing something like:

def link_facttura(self):
    if not self.id:
        return some_url/fattura/%d/ % Fattura.objects.latest().id+1
    return u""

But it's ugly and likely to cause erros once you start deleting records



来源:https://stackoverflow.com/questions/12110654/django-set-default-value-of-a-model-field-to-a-self-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!