简体   繁体   中英

Keep getting "Could not resolve URL for hyperlinked relationship using view name "songs"

I have the following model class:

# Song Model
class Song(models.Model):
    title = models.CharField(max_length=200)
    artist = models.CharField(max_length=200)
    content = models.TextField()
    user = models.ForeignKey('auth.User', related_name='songs')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):  # __unicode__ on Python 2
        return self.title + ' ' + self.artist

    class Meta:
        ordering = ('title',)

My serializers

class SongSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        fields = ('id', 'title', 'artist', 'content')
        model = Song


class UserSerializer(serializers.ModelSerializer):
    songs = serializers.HyperlinkedRelatedField(
        many=True, read_only=True,
        view_name='songs'
        )

    class Meta:
        model = User
        fields = '__all__'

and my views

class SongViewSet(viewsets.ModelViewSet):
    queryset = Song.objects.all()
    serializer_class = SongSerializer


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

I am trying to get the list of songs but I keep getting this error ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "songs"

This has been working with PrimaryKeyRelatedField but not as it is now.

routes file for reference:

router = DefaultRouter()
router.register(r'songs', views.SongViewSet)
router.register(r'users', views.UserViewSet)


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include(router.urls)),
]

Well, I was able to make it work with

view_name='song-detail'

If anyone wants to explain the why of how it works, please feel free

I'm total newbie in Django but I've faced with the same issue. I suppose that because of router prefix param is not the view name.

Documentation for the router says:

The example above would generate the following URL patterns:

URL pattern: ^users/$ Name: 'user-list'
URL pattern: ^users/{pk}/$ Name: 'user-detail'
URL pattern: ^accounts/$ Name: 'account-list'
URL pattern: ^accounts/{pk}/$ Name: 'account-detail'

Documentation for the serializer says:

view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format <modelname>-detail . required.

If you are using DefaultRouter you can try change basename='song'

from rest_framework.routers import DefaultRouter
router = DefaultRouter()

router.register('song', views.SongViewset, basename='song')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM