【问题标题】:Django Rest Framework: Get Data by FieldDjango Rest 框架:按字段获取数据
【发布时间】:2020-08-24 09:51:17
【问题描述】:

我想学习 django。

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

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

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

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

这可能吗?

我的文件:

modely.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")

urls.py

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

views.py

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

【问题讨论】:

标签: django django-rest-framework django-rest-framework-filters


【解决方案1】:

我建议选择其中一个作为标识符。在本例中,我将使用机场代码。

在 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'})

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

【讨论】:

    【解决方案2】:

    使用动作装饰器创建自定义 get 方法

    @action(detail=False, methods=['GET'], url_path='destination/(?P<pmi>\w{0,500})')
    def custom_ge(self, request, pmi):
        #Function implementation in here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 2015-01-02
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      相关资源
      最近更新 更多