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在它的只顯示該特定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__'
`
這取決於你想傳遞什麼而不是'id'。它是什麼類型?這是一個字符串嗎?或「uuid」? –
我想通過字符串「PName」。 – Nishit
最有可能你想要查詢參數,以便您可以通過其他字段進行過濾。 –