我正在为大约10个模型构建一些抽象模型。 我需要以某种方式使得在抽象模型中未声明一个字段,但必须在继承模型中声明。
怎么做? 是否有任何方法可以使用NotImplementedError
?
我正在为大约10个模型构建一些抽象模型。 我需要以某种方式使得在抽象模型中未声明一个字段,但必须在继承模型中声明。
怎么做? 是否有任何方法可以使用NotImplementedError
?
Field
name "hiding" is not permitted。这意味着,如果您想在基本抽象类中声明一个抽象属性,它是一个Field
实例,您将无法像正常的Python类继承范例那样在子类中重写它。引用文档:Field
实例(虽然非常不可能),您可以通过使用@property
装饰器来实现您想要的效果。像这样的东西应该可以工作:class Person(models.Model):
def __init__(self, *args, **kwargs):
super(Person, self).__init__(*args, **kwargs)
self.last_name
first_name = models.CharField(max_length=30)
@property
def last_name(self):
raise NotImplementedError
class Meta:
abstract = True
class Student(Person):
home_group = models.CharField(max_length=5)
last_name = "Doe" # "models.CharField()" will not work!
class BadStudent(Person):
home_group = models.CharField(max_length=5)
# "NotImplmentedError" will be raised when instantiating BadStudent()
abc.abstractproperty
。但我不确定它在Django的模型继承中如何工作。你为什么想要这样做??为什么不能在AbstractModel中声明公共字段的原因是什么?
如果你真的想这样做,请使用这里的指示: 在超类构造函数中添加子类中的方法