如何在Django Rest Framework基于类的视图中通过slug而不是id获取详细页面

y1aodyip  于 2023-03-13  发布在  Go
关注(0)|答案(1)|浏览(137)

我正在使用Django Rest Framework构建一个API,我有一个/api/localities端点,在那里显示了数据库中的所有对象。
现在我想为一个特定位置的单个页面创建端点,我想通过slug而不是id来创建端点,例如/API/localities/慕尼黑
我使用的是基于类的视图,现在我可以通过id获取单个页面,例如/API/localities/2,但我想将其更改为slug。
我该怎么做呢?
下面是我的代码:

型号.py

class Localities(models.Model):
        id_from_api = models.IntegerField()
        city = models.CharField(max_length=255, null=True, blank=True)
        slug = models.CharField(max_length=255, null=True, blank=True)
        postal_code = models.CharField(max_length=20, null=True, blank=True)
        country_code = models.CharField(max_length=10, null=True, blank=True)
        lat = models.CharField(max_length=255, null=True, blank=True)
        lng = models.CharField(max_length=255, null=True, blank=True)
        google_places_id = models.CharField(max_length=255, null=True, blank=True)
        search_description = models.CharField(max_length=500, null=True, blank=True)
        seo_title = models.CharField(max_length=255, null=True, blank=True)

        def __str__(self):
             return self.city

序列化程序.py

from rest_framework import serializers
from .models import Localities

class LocalitiesSerializers(serializers.ModelSerializer):
    class Meta:
        model = Localities
        fields = (
            "id",
            "id_from_api",
            "city",
            "slug",
            "postal_code",
            "country_code",
            "lat",
            "lng",
            "google_places_id",
            "search_description",
            "seo_title",
        )

查看次数.py

from django.shortcuts import render
from django.http import HttpResponse
from wagtail.core.models import Page
from .models import LocalityPage, Localities
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import generics

import json
import requests

from .models import Localities
from .serializers import LocalitiesSerializers

class LocalitiesAll(generics.ListCreateAPIView):
    queryset = Localities.objects.all()
    serializer_class = LocalitiesSerializers

class LocalitiesDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Localities.objects.all()
    serializer_class = LocalitiesSerializers

网址.py

from django.urls import path
from . import views

urlpatterns = [  
    path('reload', views.convert_json),  # app homepage
    path("localities/", views.LocalitiesAll.as_view()),
    path("localities/<int:pk>/", views.LocalitiesDetail.as_view()),
]
iezvtpos

iezvtpos1#

如果你想使用slug而不是id,那么首先你需要将你的URL从int:pk更新为str:slug:

path("localities/<str:slug>/", views.LocalitiesDetail.as_view())

现在将views.py文件类更新为:

class LocalitiesDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Localities.objects.all()
    serializer_class = LocalitiesSerializers
    lookup_field = 'slug'

这将帮助你达到你想要达到的目标。

相关问题