I have a series of models that look like this:
class Analysis(models.Model):
analysis_type = models.CharField(max_length=255)
def important_method(self):
...do stuff...
class SpecialAnalysis(Analysis):
class Meta:
proxy = True
def important_method(self):
...something different...
This is all pretty standard. However, what I'd like to do is automatically convert an Analysis
model to a proxy model based on the value of the analysis_type
field. For example, I'd like to be able to write code that looks like this:
>>> analysis = Analysis.objects.create(analysis_type="nothing_special")
>>> analysis.__class__
<class 'my_app.models.Analysis'>
>>> analysis = Analysis.objects.create(analysis_type="special")
>>> analysis.__class__
<class 'my_app.models.SpecialAnalysis'>
>>> analysis = Analysis.objects.get(pk=2)
>>> analysis.__class__
<class 'my_app.models.SpecialAnalysis'>
>>> # calls the ``important_method`` of the correct model
>>> for analysis in Analysis.objects.all():
... analysis.important_method()
Is this even remotely possible? A similar question was asked here, which actually gives some code for the iteration example, but it still leaves me with the question of how to get or create an instance of a proxy class from its parent. I suppose I could just override a bunch of manager methods, but I feel like there must be a more elegant way to do it.