• Django项目总结:错误日志【xxx-detail 和 lookup_field】


    环境版本

    Django Version: 3.0.8

    Python Version: 3.7.5

    Django REST framework  3.11.0

     

    报错信息

    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.

     

    出现场景

    models.py

    1 from django.db import models
    2 
    3 
    4 class Game(models.Model):
    5     g_name = models.CharField(max_length=32)
    6     g_price = models.FloatField(default=0)

    serializers.py

    1 from rest_framework import serializers
    2 from App.models import Game
    3 
    4 
    5 class GameSerializer(serializers.HyperlinkedModelSerializer):
    6     class Meta:
    7         model = Game
    8         fields = ('url', 'id', 'g_name', 'g_price')

    App/views.py

     1 from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
     2 from App.models import Game
     3 from App.serializers import GameSerializer
     4 
     5 
     6 # 使用ListCreateAPIView可以完成一个接口处理get/post两种请求
     7 class GamesView(ListCreateAPIView):
     8     queryset = Game.objects.all()
     9     serializer_class = GameSerializer
    10 
    11 
    12 # 查询单个数据 进行数据操作
    13 class GameView(RetrieveUpdateDestroyAPIView):
    14     queryset = Game.objects.all()
    15     serializer_class = GameSerializer

    App/urls.py

    1 from django.urls import path
    2 from App import views
    3 
    4 app_name = 'App'
    5 urlpatterns = [
    6     path('games/', views.GamesView.as_view()),
    7     path('games/<int:pk>/', views.GameView.as_view(), name="game-detail"),
    8 ]

    根/urls.py

    1 from django.urls import path, include
    2 
    3 urlpatterns = [
    4     path('app/', include('App.urls')),
    5 ]

    解决方法有两种

    方法一:根路由和App路由中不添加 namespace 和 app_name

    方法二:换一种路由写法

    https://docs.djangoproject.com/zh-hans/3.1/topics/http/urls/

    不使用 App/urls.py,将路由写在根路由中。

     

    根/urls.py

     1 from django.urls import path, include
     2 from App import views
     3 
     4 extra_patterns = [
     5     path('games/', views.GamesView.as_view()),
     6     path('games/<int:pk>/', views.GameView.as_view(), name="game-detail"),
     7 ]
     8 
     9 urlpatterns = [
    10     path('app/', include(extra_patterns)),
    11 ]
  • 相关阅读:
    Jquery、Ajax实现新闻列表页分页功能
    html中文字溢出处理(text-overflow)
    canvas图像绘制过程中的注意
    问题账户需求分析
    2016年秋季个人阅读计划
    阅读笔记之我们应当怎样做需求分析
    软件工程课个人总结
    人月神话阅读笔记—第四章
    人月神话阅读笔记—第三章
    人月神话阅读笔记—序言及第一、二章
  • 原文地址:https://www.cnblogs.com/dc2019/p/13461123.html
Copyright © 2020-2023  润新知