Django 多表继承因模型定义中的泄漏变量而阻塞

标签 django python-2.7 django-models list-comprehension multi-table-inheritance

class Parent(models.Model):
    pass

class RebelliousChild(Parent):
    parent_fields = [__x.name for __x in Parent._meta._fields()]

Django 1.3 回应:

django.core.exceptions.FieldError: Local field '_RebelliousChild__x' 
in class 'RebelliousChild'clashes with field of similar name from base class 'Parent'

Django 1.5 回应:

FieldError: Local field u'id' in class 'RebelliousChild' clashes with field 
of similar name from base class 'Parent'

我的第二个 react (在尝试将变量设为私有(private)之后)是删除该变量(这有效。)

parent_fields = [__x.name for __x in Parent._meta._fields()]
del __x

列表推导式 leak their control variables in Python 2 。 Django prohibits overriding parent field attributes ,这似乎以某种方式涉及,因为 Django 1.5 也有同样的问题。但在这两种情况下,泄漏的属性名称 _RebelliousChild__x 均未在 Parent 上定义。

这是怎么回事?

PS Using "list(x.name for x in Parent._meta._fields())" is prettier than "del x". See the aforementioned https://stackoverflow.com/a/4199355 about generators not leaking their control variables.

最佳答案

看看这里:https://docs.djangoproject.com/en/1.5/topics/db/models/#multi-table-inheritance

简而言之,您不需要将父字段应用于子字段(它们已经存在,但在不同的表中),您可以直接在 RebelliousChild 实例上访问它们。

关于Django 多表继承因模型定义中的泄漏变量而阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18294799/

相关文章:

python - 如何引发此异常或错误消息?

python - 当我在输入 "python manage.py runserver"后配置 django 管理工具时,我使用了哪个服务器?

python-2.7 - RuntimeError:不再支持直接调用 `rasa.core.run`。请改用 `rasa shell`

python - 为什么 PyQt5 在 Windows 7 中的 Python3.4 中导入失败并显示 `ImportError: DLL load failed`?

用于创建和更新的基于 Django 类的 View

django - 索引错误 : tuple index out of range

python - 除非按顺序,否则不会读取路径

Django:测试客户端的上下文在 shell 中为空

python - Django celery : Passing request Object to worker

python - Django celery : Celery task does not create record in DB