Search code examples
pythondjangodjango-modelsdjango-inheritance

Help a Python newbie with a Django model inheritance problem


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?


Solution

  • 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?