django - 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()
解决方案
我建议选择一个或另一个作为标识符。对于此示例,我将使用机场代码。
在 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'})
其他一切都应该按原样工作!
推荐阅读
- java - 通过 AsyncTask 中的 ID 获取 ChampionName
- java - 我可以在 jar 文件中设置新的 config.properties 文件吗?
- javascript - Firebase SDK 与 Rest API
- java - Spring Boot 2 NamedNativeQuery 找不到属性
- javascript - 使用 JQuery 和 Python 发送图像
- swift - 删除 UILable 的额外填充
- mysql - 为什么mysql和perl base64字符串编码不同?
- python - 没有 Lambda 重试的 Python 中的 AWS Lambda 处理错误
- python - 交叉验证模型拟合的可视化方法
- go - golang-echo-realworld-example-app 的存储库模式