且构网

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

Django将默认值保存在代理模型中

更新时间:2023-01-30 10:50:06

模型管理器在表级"上运行.当您通过表单创建对象时,它使用模型对象而不是模型管理器,因此您需要覆盖代理模型的 save .如果我将您的 Type2ProxyModel 修改为此,则会起作用:

A model manager operates on a "table-level". When you create an object via a form it uses the model objects and not the model manager and thus you'd need to override the save of your proxy model. If I modify your Type2ProxyModel to this it works:

class Type2ProxyModel(MyModel):
    class Meta:
        proxy = True

    objects = Type2Manager()

    def save(self, *args, **kwargs):
        self.type = 'TYPE2'
        return super(Type2ProxyModel, self).save(*args, **kwargs)