尝试创建嵌套路由时出现KeyError

时间:2020-06-15 02:28:04

标签: python django generics django-models django-rest-framework

我正在尝试创建https://dog.ceo/dog-api/克隆,但遇到一个小问题。

这是我的代码:

from django.db import models

# Create your models here.
class Breed(models.Model):
      name = models.CharField(max_length=150)


      def __str__(self):
          return self.name

class BreedImage(models.Model):
    breed = models.ForeignKey(Breed, related_name='BreedImages', on_delete=models.CASCADE)
    breedImage = models.ImageField(upload_to='photos')

序列化器

from rest_framework import serializers
from .models import Breed, BreedImage

class BreedSerializer(serializers.ModelSerializer):


    class Meta:
        model = Breed
        fields = ['name', 'BreedImages']

class BreedSerializerRandom(serializers.ModelSerializer):


    class Meta:
        model = Breed
        fields = ['id', 'BreedImages']

观看次数

from django.shortcuts import render
from rest_framework import generics
from .models import Breed
from .serializers import BreedSerializer, BreedSerializerRandom
from rest_framework.parsers import FileUploadParser, FormParser, MultiPartParser
# Create your views here.

class BreedList(generics.ListCreateAPIView):
    parser_classes = (FormParser, MultiPartParser)
    queryset = Breed.objects.all()
    serializer_class = BreedSerializer
    pagination_class = None


class BreedDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Breed.objects.all()
    serializer_class = BreedSerializer
    pagination_class = None

class BreedDetailRandom(generics.RetrieveUpdateDestroyAPIView):

    serializer_class = BreedSerializerRandom

    def get_queryset(self):
        return Breed.objects.filter(id=self.kwargs['id']).order_by('?')[0]

网址

from django.urls import path
from Breed import views

urlpatterns = [
    path('breeds/', views.BreedList.as_view()),
    path('breeds/<int:pk>/', views.BreedDetail.as_view()),
    path('breeds/<int:pk>/random', views.BreedDetailRandom.as_view()),
]

我的错误是:

KeyError at /breeds/1/random

'id'

我正在尝试创建一个嵌套的url,以从我的API上的特定犬种中获取随机图像,但我不确定是什么问题。

1 个答案:

答案 0 :(得分:1)

您的URL以pk作为参数

path('breeds/<int:pk>/random', views.BreedDetailRandom.as_view())

但鉴于您正在寻找ID

return Breed.objects.filter(id=self.kwargs['id']).order_by('?')[0]

sidenote-> order_by('?')效率低