Reputation: 2114
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?
Upvotes: 1
Views: 1389
Reputation: 4367
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.
Upvotes: 3