class WidgetType(models.Model):"""WidgetType categorizes the type of Widget"""name = models.CharField(max_length=255)slug = models.SlugField(max_length=255, editable=False)class Meta:db_table = u'widget_type'class Widget(models.Model):"""Widget is a component of WidgetType type that renders a DataStream on a defined Dashboard"""widget_type = models.ForeignKey(WidgetType)name = models.CharField(max_length=255, null=True, blank=True)class Meta:db_table = u'widget'class LineChart(Widget):"""Line Chart Widget Proxy"""class Meta:proxy = Truedef save(self, *args, **kwargs):self.widget_type = WidgetType.objects.get(slug='line-chart')super(LineChart, self).save(*args, **kwargs)
widgets = LineChart.objects.all()
>>> widgets = Widget.objects.all()>>> print widgets[<LineChart: 1>,<LineChart: 2>,<LineChart: 3>,<BarChart: 4>,<lineChart: 5>,<ScatterChart: 6>]
http://code.google.com/p/django-polymorphic-models/
Cheers
Tom
Bastian Kuberek writes:
> [...]
>
> What I need is to be able to query the Widget class and get back
> subclasses based on their type:
>
>>>> widgets = Widget.objects.all()
>>>> print widgets
> [<LineChart: 1>,<LineChart: 2>,<LineChart: 3>,<BarChart: 4>,<lineChart:
> 5>,<ScatterChart: 6>]
We do this very reliably with
http://djangosnippets.org/snippets/2091/ but I find
https://github.com/carljm/django-model-utils/blob/master/README.rst
very interesting, too.
This is a frequently-requested feature with many implementations,
yet there is no canonical solution in Django, unfortunately.
Tsch�,
Torsten.
--
Torsten Bronger Jabber ID: torsten...@jabber.rwth-aachen.de
or http://bronger-jmp.appspot.com