Creating model (table) inheritance in Django 1.8 using PostgreSQL

60 views
Skip to first unread message

Some Developer

unread,
Jul 2, 2015, 8:35:42 AM7/2/15
to django...@googlegroups.com
I have a model which defines an item and many sub-models which inherit
from it to define the type of the model. Something like this:

Product(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
name = models.CharField(max_length=255)

ProductItemText(Product):
type = models.TextField()

ProductItemBoolean(Product):
type = models.BooleanField()

etc etc. There are a lot more different sub-models for different types.

I'm a bit confused about how to generate a form based on the type that
the user wants to add to the database. Do you have to have a form each
individual sub-type or is there a nice workaround for this specific problem?

Any help is appreciated.

Vijay Khemlani

unread,
Jul 2, 2015, 8:57:02 AM7/2/15
to django...@googlegroups.com
You could dynamically create a ModelForm based on the model class:

from django.forms import ModelForm

MetaClass = type('Meta', (), {'model': ProductItemText})

MetaModelForm = type('ProductModelForm', (ModelForm, ), {'Meta': MetaClass})

form = MetaModelForm()

The only thing you would need is the model class itself ("ProductItemText" in this particular case),  I think you could even add it as a classmethod to the base Product class.







--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/55952FDF.8000604%40googlemail.com.
For more options, visit https://groups.google.com/d/optout.

Some Developer

unread,
Jul 2, 2015, 9:24:08 AM7/2/15
to django...@googlegroups.com
On 02/07/15 13:56, Vijay Khemlani wrote:
> You could dynamically create a ModelForm based on the model class:
>
> from django.forms import ModelForm
>
> MetaClass = type('Meta', (), {'model': ProductItemText})
>
> MetaModelForm = type('ProductModelForm', (ModelForm, ), {'Meta': MetaClass})
>
> form = MetaModelForm()
>
> The only thing you would need is the model class itself
> ("ProductItemText" in this particular case), I think you could even add
> it as a classmethod to the base Product class.

Hi,

Thanks for the reply.

I'm a bit confused about what this does. Can you explain a little bit.
I'd like to understand what is going on in the above code a little better.

Thanks.

Reply all
Reply to author
Forward
0 new messages