默认值和DeferredAttribute问题

时间:2018-09-24 08:02:55

标签: django django-models

我想以另一种形式设置默认值。如何正确做??????

class def_val(models.Model):

    bnumber = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return self.bnumber

class Panel(models.Model):

    barcode = models.CharField('Kod kreskowy', max_length=100, blank=True)
    producer = models.ForeignKey(PanelProducer, verbose_name='Producent', on_delete=models.CASCADE)
    size = models.ForeignKey(PanelSize, verbose_name='Rozmiar', on_delete=models.CASCADE)
    box_number = models.CharField(('Numer palety'), max_length=10, blank=True, default=def_val.bnumber)
    tested_by = models.ForeignKey(User, verbose_name='Osoba pakująca', related_name="Created_by", on_delete=models.CASCADE)
    test_date = models.DateTimeField(('Data pakowania'),default=datetime.now, blank=True)

1 个答案:

答案 0 :(得分:0)

您不能在模型中执行此操作,也不能在类级别的任何定义中执行此操作。您将需要使用__init__方法的形式来完成此操作。

class PanelForm(forms.ModelForm):
    class Meta:
        model = Panel
        fields = [...]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if 'box_number' not in self.initial:
            self.initial['box_number'] = def_val.objects.first().bnumber