【发布时间】:2010-05-26 15:28:33
【问题描述】:
经过多年的 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 管理页面吐出错误“Caught an exception while rendering: 'Category' object has no attribute 'name'
有人能指出正确的方向吗?
【问题讨论】:
标签: python django django-models django-inheritance