我正在從我的REST API在http://127.0.0.1:8000/api/category/以下回應:獲取單個記錄基於ID
[
{
"id": "17442811-3217-4b67-8c2c-c4ab762460d6",
"title": "Hair and Beauty"
},
{
"id": "18a136b5-3dc4-4a98-97b8-9604c9df88a8",
"title": "Plumbing"
},
{
"id": "2f029642-0df0-4ceb-9058-d7485a91bfc6",
"title": "Personal Training"
}
]
如果我想訪問,一個記錄,我相信我會需要去http://127.0.0.1:8000/api/category/17442811-3217-4b67-8c2c-c4ab762460d6訪問:
[
{
"id": "17442811-3217-4b67-8c2c-c4ab762460d6",
"title": "Hair and Beauty"
}
]
但是,當我嘗試這個,它會返回所有的記錄。我該如何解決這個問題?這是到目前爲止我的代碼:
urls.py
urlpatterns = [
url(r'^category/', views.CategoryList.as_view(), name="category_list"),
url(r'^category/?(?P<pk>[^/]+)/$', views.CategoryDetail.as_view(), name="category_detail")
]
views.py
class CategoryList(generics.ListAPIView):
"""
List or create a Category
HTTP: GET
"""
queryset = Category.objects.all()
serializer_class = CategorySerializer
class CategoryDetail(generics.RetrieveUpdateDestroyAPIView):
"""
List one Category
"""
serializer_class = CategorySerializer
serializers.py
class CategorySerializer(serializers.ModelSerializer):
"""
Class to serialize Category objects
"""
class Meta:
model = Category
fields = '__all__'
read_only_fields = ('id')
models.py
class Category(models.Model):
"""
Category model
"""
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
title = models.CharField(max_length=255)
def __str__(self):
return "%s" % (self.title)
爲什麼不使用django rest框架'ModelViewSets',這將解決您的問題。請在這個鏈接看看:http://www.django-rest-framework.org/api-guide/viewsets/#modelviewset –