且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django模型继承层次结构中字段的基于类的默认值

更新时间:2023-01-30 10:32:45

通过default =做得更好,但是您在这里使用的任何东西都没有办法获得你的课堂或具体的模型,要在像admin,你可以在 init ()而不是save()中设置它。

It does feel nicer to do this via default=, but anything you use there doesn't have a way to get at your class or specific model. To have it show up properly in places like the admin, you could set it in init() instead of save().

class OrderDocumentBase(PdfPrintable):
    number = models.PositiveIntegerField()

    def __init__(self, *args, **kwargs):
        super(OrderDocumentBase, self).__init__(*args, **kwargs)
        if not self.pk and not self.number:
            self.number = self.DEFAULT_NUMBER

class Invoice(OrderDocumentBase):
    DEFAULT_NUMBER = 2

class CreditAdvice(OrderDocumentBase):
    DEFAULT_NUMBER = 3