mcdmcd 发表于 2021-3-20 04:15:51

求助一个Django rest framework的问题!谢谢大神

本帖最后由 mcdmcd 于 2021-3-20 04:30 编辑

项目环境: python3.9   Django2.2


今天在学习Django rest framework框架


使用HyperlinkedModelSerializer   时   fields 加上‘url‘后,在用POST方法添加数据后就回报错:
Could not resolve URL for hyperlinked relationship using view name "game-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.

serializer.py
class GameSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
      model = Game
      fields = ('url', 'g_name', 'g_price')


views.py
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView

from App.models import Game
from App.serializers import GameSerializer


# Create your views here.
class GamesView(ListCreateAPIView):
    serializer_class = GameSerializer
    # model = Game
    queryset = Game.objects.all()


class GameView(RetrieveUpdateDestroyAPIView):
    serializer_class = GameSerializer
    queryset = Game.objects.all()



urls.py
from django.urls import path

from App import views

app_name = 'App'
urlpatterns = [
    path('games/', views.GamesView.as_view(), ),
    path('games/<int:pk>/', views.GameView.as_view(), name='game-detail'),
]

mcdmcd 发表于 2021-3-20 10:41:34

自己顶一下   求大神帮帮忙
页: [1]
查看完整版本: 求助一个Django rest framework的问题!谢谢大神