Django REST Framework: Two different ModelSerializers for the same model -



Django REST Framework: Two different ModelSerializers for the same model -

i have 1 model i've defined 2 different hyperlinkedmodelserializers:

class foo(models.model): ... class fooserializer1(serializers.hyperlinkedmodelserializer): ... class meta: model = foo fields = ('url', 'id', ...) lookup_field= 'pk' # sec view of same model api use-case class fooserializer2(serializers.hyperlinkedmodelserializer): ... class meta: model = foo fields = ('url', 'id', ...) lookup_field= 'pk'

fooserializer1 beingness used couple genericviews in 1 django app (i.e. own urls.py), , fooserializer2 modelviewset in django app. have modelviewset registered in defaultrouter along few other viewsets:

urlpatterns = patterns('', url(r'^$', 'myapp.views.api_root'), url(r'^foo1/$', views.foolist1.as_view(), name='foo1-list'), ... ) urlpatterns = format_suffix_patterns(urlpatterns) ... class fooviewset2(viewsets.readonlymodelviewset): queryset = foo.objects.all() serializer_class = fooserializer2 permission_classes = (permissions.isauthenticatedorreadonly,) def get_queryset(self): ... router = routers.defaultrouter() ... router.register(r'foo2', views.fooviewset2) ... urlpatterns = router.urls

that router's auto-generated api root displays endpoint genericview of fooserializer1 (foo1-list), instead of foo2/. if manually foo2/, results show foo serialized according fooserializer2 (which correct), url each result 1 time again displays foo1 detail view.

i tried setting get_serializer in fooviewset2, didn't work. how api-root , fooserializer2 results display urls corresponding fooviewset2?

drf fortunately allows flexibility back upwards scenario through setting few parameters.

first, set basename parameter on router entry:

router.register(r'foo2', views.foo2viewset, 'foo2')

next, set view_name in hyperlinkedmodelserializers in order not default foo-detail mentioned in docs:

class fooserializer1(serializers.hyperlinkedmodelserializer): url = serializers.hyperlinkedidentityfield( view_name='foo1-detail', ) ... urlpatterns = patterns('', url(r'^$', 'myapp.views.api_root'), url(r'^foo1/$', views.foo1list.as_view(), name='foo1-list'), url(r'^foo1/(?p<pk>[0-9]+)/$', views.foodetail1.as_view(), name='foo1-detail'), ... class fooserializer2(serializers.hyperlinkedmodelserializer): url = serializers.hyperlinkedidentityfield( view_name='foo2-detail', ) ...

django django-rest-framework

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

c# - Create a Notification Object (Email or Page) At Run Time -- Dependency Injection or Factory -

Set Up Of Common Name Of SSL Certificate To Protect Plesk Panel -