如何从抽象基类覆盖模型字段的默认值

编程入门 行业动态 更新时间:2024-10-18 20:33:30
本文介绍了如何从抽象基类覆盖模型字段的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些代码如下:

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.

更多推荐

如何从抽象基类覆盖模型字段的默认值

本文发布于:2023-07-17 02:52:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128670.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   抽象   默认值   模型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!