开发者

Set editable=False only in subclass

I have a field "name" that is automatically constructed from "first_name" and "last_name" in one of the subclasses:

from django.db import models
from django.utils.translation import ugettext_lazy as _

class Actor(models.Model):
    name = models.CharField(_('开发者_如何学Goname'), max_length=60)

class Company(Actor):
    pass

class Person(Actor):
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('e-mail address'), unique=True)

    def save(self, *args, **kwargs):
        if self.first_name or self.last_name:
            self.name = (self.first_name + ' ' + self.last_name).strip()
        else:
            self.name = self.email
        super(Person, self).save(*args, **kwargs)

I would like the "name" field to be editable in the Actor and Company models, but not in the Person model. How can I accomplish that?

I can't override the field definition by adding

name = models.CharField(_('name'), max_length=60, editable=False)

to the Person model because Django raises a FieldError ("Local field 'name' in class 'Person' clashes with field of similar name from base class 'Actor'").


Forget about editable and exclude the field in the model's ModelAdmin instead:

from django.contrib import admin

admin.site.register(Person, exclude=['name'])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜