0

目前我傳遞參數「ID」在URL中調用API和我打電話的ID的API,但是我想通過parameter.here調用API是views.py`Django的RestFramework由現場

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)

這是結果,當我通過ID在URL enter image description here`

當我通過ID在它的只顯示該特定ID結果網址不過,我需要視圖如果我通過其他領域inste廣告的id它顯示的結果基於that.so我的問題是我應該改變views.py和Urls.py。這是urls.py file`

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)

這是我serializer.py file`

from rest_framework import serializers 
 
from .models import Post 
 

 

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

 
     #fields=('ProductName','Score') 
 
     fields ='__all__'

`

+0

這取決於你想傳遞什麼而不是'id'。它是什麼類型?這是一個字符串嗎?或「uuid」? –

+0

我想通過字符串「PName」。 – Nishit

+0

最有可能你想要查詢參數,以便您可以通過其他字段進行過濾。 –

回答

0

你應該改變你URL,以便它接受字符串:

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不是唯一的,因爲它會抱怨你有一個以上的這樣的郵政。

希望它有幫助!