如何从抽象基类覆盖模型字段的默认值 [英] How to override the default value of a Model Field from an Abstract Base Class
问题描述
我有一些代码如下:
class BaseMessage(models.Model):
is_public = models.BooleanField(default=False)
# some more fields...
class Meta:
abstract = True
class Message(BaseMessage):
# some fields...
我想覆盖Message模型中的 is_public
字段的默认值,因此该模型的 True
and I'd like to override the default value of the is_public
field in the Message model so that it's True
for that model.
我已经浏览了一些相关的Django文档,并围绕模型对象戳了一下,但是我找不到正确的地方找到了。任何建议?
I've looked through some relevant Django docs and poked around the model objects but I'm having trouble finding the right place to do this. Any suggestions?
推荐答案
你可以这样做:
class BaseMessage(models.Model):
is_public = models.BooleanField(default=False)
# some more fields...
class Meta:
abstract = True
class Message(BaseMessage):
# some fields...
Message._meta.get_field('is_public').default = True
我已经做了一两次。它的作用是因为Message上的字段与BaseMessage上的字段不同。但是,我怀疑它是推荐的;-)这取决于很多django内部部件目前的工作,所以不能保证它将永远工作。
I have done this once or twice. It works, because the field on Message is a different instance than the field on BaseMessage. However, I doubt it's recommended ;-) It depends a lot on how django internals currently work, so there's no guarantee that it will work forever.
这篇关于如何从抽象基类覆盖模型字段的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!