I am using django-tastypie to create a rest API for my webapp. I want to create classes like mentioned below without typing them all out explicitly(I have more than a 100 classes)
class CityResource(ModelResource):
class Meta:
queryset = City.objects.all()
class StateResource(ModelResource):
class Meta:
queryset = State.objects.all()
etc...
I was thinking of using metaclasses in python(my approach might be wrong but still want to solve it this way as I want to see how metaclass can help me and maybe a good way to learn it in a real life problem)
I tried this:
class ClassFactory(type):
def __new__(cls, name, bases, dct):
return type.__new__(cls, name, bases, dct)
for model in get_models(app):
name = "%sResource" % model._meta.object_name
ClassFactory(name, (ModelResource, ), {'Meta':type('Meta', (), {'queryset': model.objects.all()})})
But this gives an error:
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
I googled up on this and everywhere it mentions about how if a class derives from 2 other classes that have two different metaclass then the class I make must have a metaclass that was derived from the two metaclasses[*].
- How does this error happen in my case, as I am deriving from the same class ModelResource?
- I am not sure I understand [*]
I might be solving this problem the wrong way, but need some pointers.
ClassFactory"metaclass" at all.type(name, (ModelResource, ), {...})should return a new class that's derived from ModelResource, as you want.