1👍
By default, ModelViewSet
is passing request into your serializer, so serializer can built URLs based on current domain. Without request, EntrySerializer
have no idea about domain, so it is creating domain-less URLs.
You can fix it in several ways:
-
instead of overwriting
list
method, overwrite get_queryset like this:class EntryView(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class = EntrySerializer lookup_field = 'title' def get_queryset(self): return super(EntryView, self).filter(publish=True)
-
Use get_serializer method of ModelViewSet instead of using EntrySerializer directly:
class EntryView(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class = EntrySerializer lookup_field = 'title' def list(self, request,*kwargs): queryset=Entry.objects.filter(publish=True) serializer = self.get_serializer(queryset,many=True) return Response(serializer.data)
-
pass dictionary containing current request into context kwarg of your serializer:
class EntryView(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class = EntrySerializer lookup_field = 'title' def list(self, request,*kwargs): queryset=Entry.objects.filter(publish=True) serializer = EntrySerializer(queryset,many=True, context={'request': request}) return Response(serializer.data)
First method is most recommended, last one is least recommended, because there are more default methods inside ModelViewSet that won’t be affected by changes inside list method. Also there are more default variables passed inside serializer by default.
Source:stackexchange.com