我正在尝试使用django rest框架创建一个api。我需要一个视图来列出数据表中的所有项目,另一个视图根据他们的id输出个人的数据。
列表视图适用于' api / bios /'。但是,在向网址添加ID时收到以下错误:
找不到HTTP 404 允许:GET,PUT,PATCH,DELETE,HEAD,OPTIONS Content-Type:application / json 变化:接受
{ "详细信息":"未找到。" }
views.py
from rest_framework.response import Response
from rest_framework import status
from rest_framework import generics, mixins
from api.models import Playerbios
from api.serializers import USASerializer
class USAListView(mixins.CreateModelMixin, generics.ListAPIView):
lookup_field = 'trackmanid'
serializer_class = USASerializer
def get_queryset(self):
return Playerbios.objects.all()
def perform_create(self, serializer):
serializer.save(user=self.request.user)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class USAView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'trackmanid'
serializer_class = USASerializer
def get_queryset(self):
return Playerbios.objects.all()
serializers.py
from rest_framework import serializers
from api.models import Playerbios
class USASerializer(serializers.ModelSerializer):
class Meta:
model = Playerbios
fields = '__all__'
lookup_field = 'trackmanid'
主要/ urls.py
from django.contrib import admin
from django.urls import path, include
from api.views import USAView, USAListView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/bios/', include('api.urls')),
path('api/bios/<trackmanid>/', include('api.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('', include('webapp.urls')),
]
API / urls.py
from django.conf.urls import url, include
from .views import USAView, USAListView
urlpatterns = [
url('(?P<trackmanid>)/', USAView.as_view(), name='usa-rud-view'),
url('', USAListView.as_view(), name='usa-list-view'),
]
答案 0 :(得分:1)
您是否考虑过将Viewsets
用于此API? DRF具有强大的ViewSet
,只需最少的配置即可执行所有这些功能。例如,这可以重写为:
<强> views.py 强>
class USAViewset(ModelViewSet):
queryset = Playerbios.objects.all()
serializer_class = USASerializer
lookup_field = 'trackmanid'
主要urls.py
urlpatterns = [
...
path('api/bios/', include('api.urls')),
...
]
<强> API / urls.py 强>
urlpatterns = patterns(
'',
)
router = DefaultRouter()
router.register(r'coupon', USAViewset)
urlpatterns += router.urls
DRF将完成其余的工作! 在此处阅读更多内容:http://www.django-rest-framework.org/api-guide/viewsets/
答案 1 :(得分:0)
我的猜测是你需要从主urls.py文件中删除这一行
path('api/bios/<trackmanid>/', include('api.urls'))
同时更改您的api/urls.py
以包含正则表达式。格式为?P<name>[regex]
。假设trackmanid
是一个整数,则需要在其旁边加一个\d+
正则表达式。
url('(?P<trackmanid>\d+)/', USAView.as_view(), name='usa-rud-view'),