0
votes

im getting error Could not resolve URL for hyperlinked relationship using view name "shop-detail"

in file shop/api/urls.py

router = routers.DefaultRouter()
router.register('shops', ShopView, base_name='shop')
urlpatterns = [
path('', include(router.urls)),]

file shop/api/serializers.py

class ShopSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
    view_name="shop-detail",
    lookup_field='id',)
class Meta:
    model = Shop
    fields = [
        'id',
        'url',
        'name',
    ]

what is wrong there? everything works if I dont add 'url' field.

edit:

added view code

class ShopView(viewsets.ModelViewSet):
lookup_field = 'id'
queryset = Shop.objects.all()
serializer_class = ShopSerializer
3
Can you add ShopView code?neverwalkaloner
@neverwalkaloner updatedAldon
to be honest, this should work. Maybe install django extensions, call the show_urls and paste the shop-detail url pattern.Linovia
@Aldon did you get this to work?afonso
@drec4s yes, i posted a solution, in short just removed lookup_field and it started workingAldon

3 Answers

0
votes

You are registering shops so the default name for the detail view will be shops-detail while you use shop-detail. Note the missing "S"

Fix that with:

class ShopSerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.HyperlinkedIdentityField(
        view_name="shops-detail",
        lookup_field='id',)
0
votes

In HyperlinkedModelSerializer by default the serializer will include a url field instead of a primary key field. Please see the documentation.

class ShopSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Shop
        fields = [
          'id',
          'url',
         'name',
        ]
0
votes

Found a problem, lookup_field in view was not needed.

class ShopView(viewsets.ModelViewSet):
    queryset = Shop.objects.all()
    serializer_class = ShopSerializer