How Api Root navigation links are created

24 views
Skip to first unread message

pa...@betzit.com

unread,
Jan 1, 2017, 4:58:28 AM1/1/17
to Django REST framework
Hi,

Still learning the ins and outs of Django REST framework and was faced with the following problem which I didn't found an answer to in the documentation.

I have model Post that represents generic social media post and I'm trying to create two different kinds of JSON representations to it. One which has more nested information and one which more simplistic and lightweight.

The problem is that both of those get the same URL in Api Root navigation listing. All relevant information can be found underneath. 
Am I missing something obvious? Is there a generally better way to achieve same results?

I'd be very happy if you could point me to right direction.


Api Root navigation gives two serializers the same URL


{
 
...
 
"feed": "http://localhost:8000/post/",  <--- HERE
 
"post": "http://localhost:8000/post/",  <--- HERE
 
"like": "http://localhost:8000/like/",
 
"comment": "http://localhost:8000/comment/",
 
...
}





from urls.py

router
= routers.DefaultRouter()

router
.register(r'feed', views.FeedViewSet)
router
.register(r'post', views.PostViewSet)






from views.py

class FeedViewSet(viewsets.ModelViewSet):
    queryset
= Post.objects.all()
    serializer_class
= FeedSerializer


class PostViewSet(viewsets.ModelViewSet):
    queryset
= Post.objects.all()
    serializer_class
= PostSerializer



from serializers.py


class FeedSerializer(serializers.ModelSerializer):
   comments
= CommentWithAuthorDetailsSerializer(many=True, read_only=True)
   author
= AuthorSerializer(read_only=True)

     
class Meta:
           model
= Post
            fields
= ('author', 'message', 'number_of_likes', 'date', 'comments')


class PostSerializer(serializers.ModelSerializer):
    comments
= serializers.PrimaryKeyRelatedField(many=True, read_only=True)

   
class Meta:
        model
= Post
        fields
= ('author', 'message', 'number_of_likes', 'date', 'comments')








Marco Silva

unread,
Jan 3, 2017, 4:19:35 AM1/3/17
to Django REST framework
you could use something like this to have an extra route on your viewset

or if you prefer, something like this https://github.com/rsinger86/drf-flex-fields that i saw recently on this mailing list

pa...@betzit.com

unread,
Jan 11, 2017, 11:30:10 AM1/11/17
to Django REST framework
Thanks for your help.

Solution for the original problem was to specify base_name for the other viewset
while registering it for the router like this:

router.register(r'feed', views.FeedViewSet, base_name='feed')
router
.register(r'post', views.PostViewSet)
Reply all
Reply to author
Forward
0 new messages