帮助 Python 新手解决 Django 模型继承问题
经过多年的 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 管理页面吐出错误“渲染时捕获异常:‘类别’对象没有属性‘名称’
有人能给我指出正确的方向吗?
I'm working on my first real Django project after years of PHP programming, and I am running into a problem with my models. First, I noticed that I was copying and pasting code between the models, and being a diligent OO programmer I decided to make a parent class that the other models could inherit from:
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
So far so good. Now all my other models extend "Common" and have names and dates like I want. However, I have a class for "Categories" were the name has to be unique. I assume there should be a relatively simple way for me to access the name attribute from Common and make it unique. However, the different methods I have tried to use have all failed. For example:
class Category(Common):
def __init__(self, *args, **kwargs):
self.name.unique=True
Causes the Django admin page to spit up the error "Caught an exception while rendering: 'Category' object has no attribute 'name'
Can someone point me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,Django 不允许这样做。
请参阅文档: http ://docs.djangoproject.com/en/1.1/topics/db/models/#field-name-hiding-is-not-permission
也在其他问题中得到回答,例如:在 Django - 模型继承 - 是否允许您覆盖父模型的属性?
No, Django doesn't allow that.
See the docs: http://docs.djangoproject.com/en/1.1/topics/db/models/#field-name-hiding-is-not-permitted
Also answered in other questions like: In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
你的
Common
类中有一个小错误应该是
You have a small mistake in your
Common
classshould be
请注意,UNIQUE 约束实际上与 Django 无关,因此您可以随意将其添加到数据库表中。您还可以使用 post-syncdb 挂钩来实现此目的。
Note that UNIQUE constraint in fact has nothing to do with Django, so you're free to add it in your database table. You can also use post-syncdb hook for that purpose.
尝试使用 Meta.unique_together 强制其进入自己的唯一索引。如果做不到这一点,最简单的方法可能是创建两个单独的抽象类,一个具有唯一的字段,另一个不具有唯一的字段。
Try using
Meta.unique_together
to force it into its own unique index. Failing that, it's probably easiest to create two separate abstract classes, one with the field unique and one not.