python - Django REST Framework - pass model to ViewSet via router -



python - Django REST Framework - pass model to ViewSet via router -

i'm trying create rest-modelviewset has no model predefined, takes model when registered router. need dynamically add together models rest-api, without configuring new viewsets or serializers.

my thought pass model in kwargs of __init__, can't figure out how correctly this. here tried:

//viewset class themeviewset(viewsets.modelviewset): def __init__(self, **kwargs): self.model = kwargs['model'] self.serializer_class = none super(themeviewset, self).__init__(**kwargs) def get_serializer_class(self): if self.serializer_class not none: homecoming self.serializer_class class themeserializer(serializers.hyperlinkedmodelserializer): class meta: model = self.model self.serializer_class = themeserializer homecoming self.serializer_class //router: router = routers.defaultrouter() router.register(r'mytheme', themeviewset(model=mytheme), base_name='mytheme')

now, if seek print self.model in __init__, correctly shows <class 'myapp.models.mytheme'> in console, django still returns error:

attributeerror @ /api/mytheme/ method available on view class.

this error raised classonlymethod-decorator. don't know create of this, there way pass model __init__, or there different approach can try?

(i know wq.db.rest has router want, don't want utilize wq. haven't tried tastypie, create easier/possible?)

thanks in advance!

django rest framework expects a viewset class passed router, not view instance. because instance has created each request, prevents lot of ugly issues shared state , follows standard django class-based views.

you may have improve luck having method creates customized viewset class based on model passed it:

class themeviewset(viewsets.modelviewset): @classmethod def create_custom(cls, **kwargs): class customviewset(cls): model = kwargs["model"] queryset = kwargs["model"].objects.all() homecoming customviewset

note i'm setting queryset view, , drf no longer accepts model since 2.4 released.

this create new class each time called, , model automatically set model passed it. when registering router, like:

router.register(r'mytheme', themeviewset.create_custom(model=mytheme), base_name='mytheme')

this way still passing viewset class router, customized model passed in. must create sure set base_name, or router won't able generate view names , run errors.

python django python-2.7 django-models django-rest-framework

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -