0

I have a base Django model, and proxy models that subclass it. They override all methods. I need to iterate over all the instances of the base model (i.e. for i in BaseModel.objects.all()), but be able to call the methods of their corresponding proxy classes instead of the placeholder methods declared in the base class.

How do I approach this? I actually have a model field which can determine which proxy model corresponds to each particular instance. Maybe I can make use of it and cast the base class into the subclass somehow? I'm at a loss.

EDIT: I've had a look at this question and have managed to change the class by writing to self.__class__. However, is that safe to use with Django?

Community
  • 1
  • 1
avramov
  • 2,119
  • 2
  • 18
  • 41
  • I'm not sure I understand... can you post exemplary code? – XORcist Aug 07 '12 at 21:05
  • My case is actually quite similar to [this question](http://stackoverflow.com/questions/7526088/django-model-polymorphism-with-proxy-inheritance?rq=1). Although I'm not sure I get the pattern where they change the value of `self.__class__` – avramov Aug 07 '12 at 21:15

1 Answers1

2
proxymodels = {"Foo": FooModel, "Bar": BarModel}    

for o in BaseModel.objects.all():
    proxymodels[o.type].method_name(o, *args, **kwargs)

The methods are called on the proxy models (the classes), passing the BaseModel instances as first argument plus any additional arguments you want to pass. That way the methods are called as if they were called on an instance of a proxy model.

PS: re-assigning self.__class__ seems very hackish to me.

XORcist
  • 4,288
  • 24
  • 32