如何更改 Django 模型子类中的字段参数?
假设我有一些 Django 模型,它是一个抽象基类:
class Foo(models.Model):
value=models.IntegerField()
class Meta:
abstract = True
它有两个派生类,我希望每个子类的字段默认值都不同。我不能简单地覆盖该字段
class Bar(Foo):
value=models.IntegerField(default=9)
,因为 Django 不允许您覆盖子类中的字段。我看过有关尝试更改可用选项的帖子,但在这种情况下,我最关心的是更改默认值。有什么建议吗?
Let's say I have some Django model that is an abstract base class:
class Foo(models.Model):
value=models.IntegerField()
class Meta:
abstract = True
and it has two derived classes, where I'd like the default value of the field to be different for each child classes. I can't simply override the field
class Bar(Foo):
value=models.IntegerField(default=9)
because Django won't let you override fields in subclasses. I've seen posts about trying to changes available choices, but in this case I care mostly about changing the default value. Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
按照另一个答案中的建议重新定义保存方法的问题是,在保存模型对象之前,不会设置您的值。
不存在此问题的另一个选择是在子类(Bar 类)中重新定义 __init__ :
The problem with redefining the save method as suggested in the other answer is that your value will not be set until you save your model object.
Another option that doesn't have this problem is to redefine the
__init__
in the child class (Bar class):请参阅 https://stackoverflow.com/a/6379556/15690:
您实际上可以按如下方式执行此操作:
See https://stackoverflow.com/a/6379556/15690:
You can actually do this as follows:
我认为你想要做的事情是不可能的,至少在 Django 中是不可能的。您必须将 Django 中的继承视为超类的外键(几乎就是这样),并且您无法更改 FK 关系中属性的默认值。
因此,您能做的最好的事情就是重新定义
save()
方法。它会类似于:And, in Foo (super-class):
以避免数据库出现 NOT NULL 问题。
I think that what you're trying to do is not possible, at least not in Django. You have to see inheritance in Django as a ForeignKey to the super-class (that's pretty much it), and you can't change the default value of an attribute in a FK relation.
So, the best thing you could do is to redefine the
save()
method. It would be something like:And, in Foo (super-class):
to avoid NOT NULL problems with the database.
这定义了一个元类(和一个基类),为所有子类提供给定类型的字段,默认值可以在子类中设置,但不一定是:
除非你有一堆子类和/或多个与 BaseTextFieldClass 相关的方法/属性和假设,这可能有点矫枉过正......但它应该按照OP的要求去做。
This defines a metaclass (and a base class) that provides all subclasses a field of a given type, with defaults that can be set in the subclass, but don't have to be:
Unless you have a bunch of subclasses and/or multiple methods/attributes and assumptions that tie into the BaseTextFieldClass, this is probably overkill... but it should do what OP requested.
这可能是一个较新的功能,但在 Django
4.2.4
中,我可以重新定义该字段,并且 Django 会在迁移文件中正确地重新创建它。It is likely a newer feature, but in Django
4.2.4
, I am able to just redefine the field and Django properly recreates it in the migration file.