1

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

2 回答 2

2

您不能使用default参数执行此操作。最好的办法是覆盖该save方法:

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)
于 2012-08-24T13:53:20.757 回答
0

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

于 2012-08-24T13:49:18.370 回答