mjkaufer
mjkaufer

Reputation: 4206

Django Extend Model with Optional Fields

I have a django model that looks something like

class Person(models.Model):
    name = models.CharField(max_length=100)
    favorite_color = models.CharField(max_length=100)
    favorite_candy = models.CharField(max_length=100)

and I want to make a template model for it. Basically, I want a model that can have an arbitrary amount of Person's fields filled out. For instance, say I wanted to have a template for Person that likes chocolate - I'd say something like chocolate_template = PersonTemplate(favorite_color='chocolate') and if I wanted someone whose name is Gerald, I could say gerald_template = PersonTemplate(name='Gerald'). The thought is that I could use these template objects to later pre-fill a Person creation form.

My main question is an implementation question. It's totally possible for me to make a template like so

class PersonTemplate(models.Model):
    name = models.CharField(max_length=100, blank=True)
    favorite_color = models.CharField(max_length=100, blank=True)
    favorite_candy = models.CharField(max_length=100, blank=True)

but the code is horrible in that I have to manually copy-paste the contents of the Person class. This means that if I change Person, I have to remember to update PersonTemplate. I was wondering if there's a prettier way to make a 'child' of a model where all of the fields are optional. Setting all of the fields of Person to blank=True and adding an isTemplate field is also a no-no because Person and PersonTemplate should be two different entities in the database. Any thoughts on this?

Upvotes: 0

Views: 933

Answers (1)

MaximeK
MaximeK

Reputation: 2061

Yes of course :)

class PersonTemplate(Person):
    field = models.CharField(max_length=100, blank=True)

Its mean you have every fields from Person and you can add more specific fields for PersonTemplate

class Person(models.Model):

Already extend from Model, its why you have access to created, modified, id, pk....

What is good its PersonTemplate 'extend' Person who 'extend' Model.

Since Django 1.10 you can overrride field like that :

class PersonTemplate(Person):
    favorite_color = models.CharField(max_length=100, blank=True)
    favorite_candy = models.CharField(max_length=100, blank=True)

Upvotes: 1

Related Questions