reZach
reZach

Reputation: 9459

Django model inheriting from different models, which each inherit from a single class

I am creating a form with Django. This form's ModelForm is built upon multiple models that inherit from base models. The structure of the models is similar to this:

class BaseModel(models.Model):
    first_name = models.CharField("First name", max_length=20)
    middle_name = models.CharField("Middle name", max_length=20)
    last_name = models.CharField("Last Name", max_length=20)
    email = models.EmailField("Email address")
    phone = models.CharField("Phone number", max_length=16)

Is inherited by

class EmployerModel(BaseModel):
    company = models.CharField("Company", max_length=20)

and..

class AdvisorModel(BaseModel):
    department = models.CharField("Department", max_length=20)

which is contained in my highest level model (the model that is used in my ModelForm):

class FormModel(EmployerModel, AdvisorModel):
    another_field = models.CharField(max_length=20)
    and_another_field = models.CharField(max_length=20)

#...

class FormModelForm(forms.ModelForm):

    class Meta:
        model = FormModel

Can I take this approach while making the form and avoid ORM errors because I have duplicate field names? Is there a way to separate and say; "THESE fields are for a 'Employer'; THESE fields are for an 'Advisor'?"

EDIT

It looks like I need to go with abstract base classes, but I don't know if that fixes the multiple inheritance problem.

Upvotes: 0

Views: 77

Answers (1)

Steve K
Steve K

Reputation: 11369

Go abstract with parent models, I've successfully written models with this kind of definition:

class Content(ModeratedModel, NullableGenericModel, RatedModel, PicturableModel, PrivacyModel, CommentableModel):
    pass

and ModelForms using Content as a model work fine.

Upvotes: 1

Related Questions