Reputation: 1169
say i have
class Visualizer(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, null=True, blank=True )
title = models.CharField(max_length=255)
description = models.TextField()
feed = models.ForeignKey(Feed)
channels = models.ManyToManyField(Channel)
And in my project there can be any number of visualizers that can have extra attributes... like one visualizer can have a 'base_color' extra attribute, and for another 'change_by_type' extra attribute... etc.. as:
#there can be 5 to 10 visualizer types VisualizerA, VisualizerB ...
class VisualizerA(models.Model):
#base visualizer attributes
base_color = models.CharField()
For now i am doing by adding an attributes text field to the base Visualizer model not adding any sub classes and keep the properties as json string. But i am having hard times with the forms... Is there a better way?
Is subclassing a choice? (But there can be 5 or 10 types of visualizer )
i need a way of doing this right...
Upvotes: 0
Views: 59
Reputation: 680
Depending or your requirements "Django dynamic model fields" may be the solution. See post Django dynamic model fields
In terms of of inheritance you can have Model inheritance with specialized Forms
Here is "Advanced Django Forms Usage" http://www.slideshare.net/pydanny/advanced-django-forms-usage
and/or Forms inheritance with common Model see post http://pydanny.com/overloading-form-fields.html
Upvotes: 1
Reputation: 20569
Subclassing is imo best solution, in database You will have 1 table for all Visualizers with all fields from base class and 1 table for each child class with id column that will have same values as in base class and columns from child class fields. It's one to one relation under the hood, but when You save new instance of child model, django will automatically make corresponding field in base model.
More here: Django model interhitance
Upvotes: 0