使用Django在Restful路径上获取特定对象

时间:2016-04-02 19:58:13

标签: python django django-rest-framework

我的代码:

API / urls.py

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")
]

API / views.py

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)

API / serializers.py

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个模型,简称titlecontentslug。我想使用 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值时,我仍然得到相同的输出,这意味着我仍然得到所有对象。我不知道我做错了什么。

环境

  • django 1.9.5
  • python 3.5.1
  • djangorestframework 3.3.3

1 个答案:

答案 0 :(得分:2)

您需要终止第一个正则表达式,否则它匹配以“条目”开头的所有内容。

r"^entries/$"