django add_to_class() 使模型继承/MRO 工作错误
通过 add_to_class() 添加字段时,我的模型存在继承问题。 我有一个模型 File(models.Model)
和 Image(File)
- 这些来自 django-filer。
在我的应用程序中,我导入它们并添加字段和方法:
def method_x(self):
print "x"
File.add_to_class("expiration_date", models.DateField(null=True, blank=True))
File.add_to_class("method_x", method_x)
图像应该继承这两者,但它只获取方法,而不获取字段:
>>> some_file = File.objects.get(id=8)
>>> some_image = Image.objects.get(id=8)
>>>
>>> print some_file.expiration_date # this works
... None
>>>
>>> some_image.metgod_x() # this works
>>> x
>>>
>>> print some_image.expiration_date # and this not
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Image' object has no attribute 'expiration_date'
有任何线索吗?
I have a problem with inheritance on my models when adding fields via add_to_class().
I have a models File(models.Model)
and Image(File)
- these come from django-filer.
In my app I'm importing them and adding fields and methods:
def method_x(self):
print "x"
File.add_to_class("expiration_date", models.DateField(null=True, blank=True))
File.add_to_class("method_x", method_x)
Image should inherit both of those but it gets only the method(s), not field(s):
>>> some_file = File.objects.get(id=8)
>>> some_image = Image.objects.get(id=8)
>>>
>>> print some_file.expiration_date # this works
... None
>>>
>>> some_image.metgod_x() # this works
>>> x
>>>
>>> print some_image.expiration_date # and this not
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Image' object has no attribute 'expiration_date'
Any clue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您模型的
add_to_class
不会将该字段添加为属性。它只是在您的字段上调用 contribute_to_class
:django/db/models/base. py#L218
你的字段
contribute_to_class
也不这样做。它只是将该字段添加到模型的_meta
成员中:django/db/models/fields/__init__.py#L234
Your model's
add_to_class
does not add the field as an attribute. it just callscontribute_to_class
on your field:django/db/models/base.py#L218
Your field's
contribute_to_class
does not do it either. It just adds the field to the model's_meta
member:django/db/models/fields/__init__.py#L234