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/