Django RestFramework通过Field调用Api

时间:2017-10-11 12:43:34

标签: python-3.x django-models django-rest-framework django-views django-urls

目前我传递参数' id'在网址中我通过id调用API但是我想通过参数调用API。这是views.py`



class post_list(APIView):

    def get(self,request,format=None):
        post_resource=PostResource()
        dataset=Dataset()
        post = Post.objects.all()
        serializer = PostSerializer(post, many=True)
        a=[]
        for row in post:
            a.append(row)

        return Response(serializer.data)

    def post(self,request,format =None):
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)




class post_detail(APIView):
    def get_object(self, pk):
        try:
            return Post.objects.get(pk=pk)
        except Post.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        post = self.get_object(pk)
        serializer = PostSerializer(post)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = PostSerializer(snippet,    data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        post = self.get_object(pk)
        post.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)




这是我在url enter image description here`

中传递id时的结果

当我在网址中传递ID时,它只显示该特定的ID结果,但是我需要查看如果我通过其他字段而不是ID它会显示基于该结果的结果。所以我的问题是我应该在views.py和Urls.py中更改什么。这是urls.py文件`



from django.conf.urls import url
from api import views
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    url(r'^post/$', views.post_list.as_view()),
    url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail.as_view()),

]
urlpatterns=format_suffix_patterns(urlpatterns)
&#13;
&#13;
&#13;

这是我的serializer.py文件`

&#13;
&#13;
from rest_framework import serializers
from .models import Post


class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post

        #fields=('ProductName','Score')
        fields ='__all__'
&#13;
&#13;
&#13;

`

1 个答案:

答案 0 :(得分:0)

您应该更改您的网址,使其接受字符串:

 url(r'^post/(?P<pname>[a-zA-Z0-9]+)/$', views.post_detail.as_view()) 

然后更改您的get_object方法:

def get_object(self, pname):
    try:
        return Post.objects.get(pname=pname)
    except Post.DoesNotExist:
        raise Http404

但是如果pname不是唯一的话,你会发出问题,因为它会抱怨你有多个这样的帖子。

希望它有所帮助!