首页 > 解决方案 > Django Rest 框架:按字段获取数据

问题描述

我想学习django。

我的第一个学习项目是一个 django + rest framework api。

我想通过机场代码获取目的地。不是按 pk / id

目前,当我调用 /api/destination/1 时,我得到 id 为 1 的目的地

我想要 /api/destination/PMI 或 /api/destination/mallorca 之类的东西,作为响应,我只想使用代码 PMI 或名称 mallorca 获取目的地。

这可能吗?

我的文件:

模型.py

class Destination(models.Model):
    name = models.CharField(max_length=50)
    code = models.CharField(max_length=3)
    country = models.CharField(max_length=50)
    image = models.FileField()

序列化程序.py

class DestinationSerializer(serializers.ModelSerializer):

class Meta:
    model = Destination
    fields = ("id", "name", "code", "country", "image")

网址.py

router = DefaultRouter()
router.register(r'destination', DestinationViewSet)

视图.py

class DestinationViewSet(viewsets.ModelViewSet):
    serializer_class = DestinationSerializer
    queryset = Destination.objects.all()

标签: djangodjango-rest-frameworkdjango-rest-framework-filters

解决方案


我建议选择一个或另一个作为标识符。对于此示例,我将使用机场代码。

在 urls.py 中,您需要从路由器切换到 urlpattern - 请记住在您的project.urls文件中注册它!

from django.urls import path

urlpatterns = [path('destination/<code>/', DestinationViewSet.as_view())]

在您的视图中,您可能只想切换到普通视图并调用 get() 方法。

from destinations.api.serializers import DestinationSerializer
from destinations.models import Destination
from rest_framework import views
from rest_framework.response import Response

class DestinationView(views.APIView):
    def get(self, request, code):
        destination = Destination.objects.filter(code=code)
        if destination:
            serializer = DestinationSerializer(destination, many=True)
            return Response(status=200, data=serializer.data)
        return Response(status=400, data={'Destination Not Found'})

其他一切都应该按原样工作!


推荐阅读