zoukankan      html  css  js  c++  java
  • 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 ]
  • 相关阅读:
    JavaScript文件加载器LABjs API详解 转
    AMD及requireJS 转
    C#中数组、ArrayList和List三者的区别 转
    CSS魔法堂:那个被我们忽略的outline
    CSS魔法堂:改变单选框颜色就这么吹毛求疵!
    CSS魔法堂:display:none与visibility:hidden的恩怨情仇
    CSS魔法堂:一起玩透伪元素和Content属性
    CSS魔法堂:稍稍深入伪类选择器
    CSS魔法堂:更丰富的前端动效by CSS Animation
    CSS魔法堂:Transition就这么好玩
  • 原文地址:https://www.cnblogs.com/dc2019/p/13461123.html
Copyright © 2011-2022 走看看