经过多年的 PHP 编程,我正在开发我的第一个真正的 Django 项目,但我的模型遇到了问题。首先,我注意到我在模型之间复制和粘贴代码,作为一个勤奋的 OO 程序员,我决定创建一个其他模型可以继承的父类:
class Common(model.Model):
name = models.CharField(max_length=255)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class Meta:
abstract=True
到目前为止一切顺利。现在我所有的其他模型都扩展了“Common”并具有我想要的名称和日期。但是,我有一个“类别”类,名称必须是唯一的。我假设应该有一种相对简单的方法让我从 Common 访问 name 属性并使其唯一。但是,我尝试使用的不同方法都失败了。例如:
class Category(Common):
def __init__(self, *args, **kwargs):
self.name.unique=True
导致 Django 管理页面吐出错误“渲染时捕获异常:'Category' 对象没有属性 'name'
有人能指出我正确的方向吗?
请您参考如下方法:
不,Django 不允许这样做。
查看文档:http://docs.djangoproject.com/en/1.1/topics/db/models/#field-name-hiding-is-not-permitted
还回答了其他问题,例如:In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
