我的代码:
from django.conf.urls import url
from api import views
urlpatterns = [
url(r"^entries", views.EntryList.as_view(), name="api-entries-list"),
url(r"^entries/(?P<pk>[0-9]+)/$", views.EntrySingle.as_view(), name="api-entry")
]
from django.shortcuts import render
from django.http import Http404
from blog.models import Entry
from api.serializers import EntrySerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
class EntryList(APIView):
def get(self, request, format=None):
entries = Entry.objects.all()
serializer = EntrySerializer(entries, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = EntrySerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class EntrySingle(APIView):
def get_object(self, pk):
try:
return Entry.objects.get(pk=pk)
except Entry.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
entry = self.get_object(pk)
serializer = EntrySerializer(entry)
return Response(serializer.data)
def put(self, request, pk, format=None):
entry = self.get_object(pk)
serializer = EntrySerializer(entry, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
entry = self.get_object(pk)
entry.delete()
return Response(status=HTTP_204_NO_CONTENT)
from blog.models import *
from cvitae.models import *
from activities.models import *
from rest_framework import serializers
class EntrySerializer(serializers.ModelSerializer):
class Meta:
model = Entry
fields = ("title", "slug")
我有一个名为blog
的应用,其中包含Entry
个模型,简称title
,content
和slug
。我想使用 Django Rest Framework 来获取,放置或删除我的条目。代码如上。当我触发/api/entries
时,它没关系,它提供了数据库中的所有Entry
模型实例。
[
{
"title": "And Maybe This is Another One",
"slug": "and-maybe-this-is-another-one"
},
{
"title": "Another Topic Here",
"slug": "another-topic-here"
},
{
"title": "An Example Title",
"slug": "an-example-title"
}
]
但是,当我确实想要Entry
实例的pk
值时,我仍然得到相同的输出,这意味着我仍然得到所有对象。我不知道我做错了什么。
答案 0 :(得分:2)
您需要终止第一个正则表达式,否则它匹配以“条目”开头的所有内容。
r"^entries/$"