views:

394

answers:

3

Let's say that I have a model Foo that inherits from SuperFoo:

class SuperFoo(models.Model):
    name = models.CharField('name of SuperFoo instance', max_length=50)
    ...

class Foo(SuperFoo):
    ... # do something that changes verbose_name of name field of SuperFoo

In class Foo, I'd like to override the verbose_name of the name field of SuperFoo. Can I? If not, is the best option setting a label inside the model form definition to get it displayed in a template?

+3  A: 

Your best bet would be setting/changing the label in the form itself. Referring to the name field of the Foo model (eg. by looking it up in Foo._meta.fields) will actually give you a reference to the name field of SuperFoo, so changing its verbose_name will change it in both models.

Also, adding a name field to the Foo class won't work either, because...

Overriding fields in a parent model leads to difficulties in areas such as initialising new instances (specifying which field is being intialised in Model.__init__) and serialization. These are features which normal Python class inheritance doesn't have to deal with in quite the same way, so the difference between Django model inheritance and Python class inheritance isn't merely arbitrary.

Steef
+5  A: 

A simple hack I have used is:

class SuperFoo(models.Model):
    name = models.CharField('name of SuperFoo instance', max_length=50)
    ...

class Foo(SuperFoo):
    ... # do something that changes verbose_name of name field of SuperFoo
Foo._meta.get_field('name').verbose_name = 'Whatever'
Gerry
A: 

Wouldn't the ideal way of doing it something in the metaclass of the submodel? Like in the __init__() method, checking for the field and changing its properties? I tried a couple of ways to do it, but it seems to clash with the Model's own _meta property.

Any idea?

saverio