I’m using django-tastypie and I need to create classes like this from my django models:
class MyModelResource(ModelResource):
class Meta:
queryset = MyModel.objects.all()
allowed_methods = ['get']
Since I have a lot of models in my django app I don’t want to repeat myself, and use type() function instead to create all that resource classes. The problem is I don’t know how to deal with this inner “Meta” class.
Can you give me an example of how to dynamically create a class with inner class using type()?
The inner class,
Meta, is just another attribute as far asMyModelResourceis concerned.Methods are also just attributes as far as
MyModelResourceis concerned. Actually, you define a function inMyModelResource.__dict__, and the Python attribute lookup mechanismcauses
inst.mymethodto return a bound method.There is no problem referring to
MyModelResourcein thesupercallbefore
MyModelResourceis defined, because name lookups are performed at run time, not at the timemymethodis defined.You are absolutely correct that
is wrong. This will spoil all that is good about
super. IfMyModelResourcewere to be subclassed, and an instance of the subclass were to callmymethod, then Python would fall into an infinite loop.