我正在编写一个像报纸一样工作的Django应用程序。我有文章,然后我有在某些上下文中出现的那些文章的自定义版本。所以,我可以在报纸的头版上看到一篇文章的版本,该文章的文章原始标题较短。所以我有:
class Article(models.Model):
""" A newspaper article with lots of fields """
title = models.CharField(max_length=255)
content = models.CharField(max_length=255)
# Lots of fields...
我想要一个CustomArticle对象作为文章的代理,但有一个可选的替代标题:
class CustomArticle(Article):
""" An alternate version of a article """
alternate_title = models.CharField(max_length=255)
@property
def title(self):
""" use the alternate title if there is one "
if self.custom_title:
return self.alternate_title
else:
return self.title
class Meta:
proxy = True
# Other fields and methods
不幸的是,我无法向代理添加新字段:
TypeError:包含代理模型“CustomArticle”
不允许的模型字段的抽象基类
所以,我可以这样做:
class CustomArticle(models.Model):
# Other methods...
original = models.ForeignKey('Article')
def __getattr__(self, name):
if hasattr(self.original):
return getattr(self.original, name)
else:
return super(self, CustomArticle).__getattr__(name)
但不幸的是,__getattr__
似乎不适用于Django模型。 Article类中的字段可能会更改,因此在CustomArticle中为每个字段创建@property
方法是不切实际的。这样做的正确方法是什么?
答案 0 :(得分:2)
看起来这可能适用于__getattr__
:
def __getattr__(self, key):
if key not in ('original', '_ original_cache'):
return getattr(self.original, key)
raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, key))
答案 1 :(得分:1)
如何使CustomArticle成为Article的子类? Django模型确实支持继承!看看:https://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance
答案 2 :(得分:1)
尝试这样的事情:
class CustomArticle(models.Model):
# Other methods...
original = models.ForeignKey('Article')
def __getattr__(self, name):
return getattr(self.original, name)