gpt4 book ai didi

python - Django - 如何使实现字段成为必需的?

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:23 25 4
gpt4 key购买 nike

我正在为大约 10 个模型构建一些抽象模型。我需要以某种方式使 1 个字段未在抽象模型中声明,但必须在继承模型中声明。怎么做?有什么方法可以使用 NotImplementedError 吗?

最佳答案

如果不深入研究 Django,恐怕没有一种简单的方法可以实现这一点。

主要原因是Field name "hiding" is not permitted在 Django 。这意味着如果你想在基础抽象类中声明一个抽象属性,它是一个Field。例如,与正常的 Python 类继承范例相反,您将无法在子类中重写它。引用文档:

In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this is not permitted for attributes that are Field instances (at least, not at the moment). If a base class has a field called author, you cannot create another model field called author in any class that inherits from that base class.

Overriding fields in a parent model leads to difficulties in areas such as initializing new instances (specifying which field is being initialized in Model.init) and serialization. These are features which normal Python class inheritance doesn't have to deal with in quite the same way, so the difference between Django model inheritance and Python class inheritance isn't arbitrary.

This restriction only applies to attributes which are Field instances. Normal Python attributes can be overridden if you wish. It also only applies to the name of the attribute as Python sees it: if you are manually specifying the database column name, you can have the same column name appearing in both a child and an ancestor model for multi-table inheritance (they are columns in two different database tables).

Django will raise a FieldError if you override any model field in any ancestor model.

但是,如果该属性不是 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 的模型继承一起使用。

关于python - Django - 如何使实现字段成为必需的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com