[Django]-Why can't Django REST Framework's HyperlinkedModelSerializer form URL?

7👍

Inspired by clues revealed by Kunkka’s answer, I have a solution that looks like this:

class TaskSerializer(serializers.HyperlinkedModelSerializer):

    url = serializers.HyperlinkedIdentityField(view_name="task:task-detail")

    class Meta:
        model = Task
        fields = ('url', 'pk', 'short_desc', 'scheduled_date')

I.e. I’ve added an url = [...] line to the serializer I originally posted in my question. This solves the lookup problem which was presumably caused by DRF not knowing that ‘task-detail’ is actually in the ‘task’ namespace.

Any better solutions?

👤Bezewy

3👍

Can you try this?

class TaskSerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.SerializerMethodField()
    class Meta:
        model = Task
        fields = ('pk','url', 'short_desc', 'scheduled_date')

    def get_url(self,obj):
        request = self.context['request']
        return = {'self':reverse('task-detail',kwargs={'pk':obj.pk},request=request)}

Leave a comment