2016-05-31 84 views
0

我正在從我的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) 
+0

爲什麼不使用django rest框架'ModelViewSets',這將解決您的問題。請在這個鏈接看看:http://www.django-rest-framework.org/api-guide/viewsets/#modelviewset –

回答

2

你的第一個正則表達式,r'^category/',既是一個URL匹配有和沒有一個UUID。

你應該在最後固定在那裏:

r'^category/$' 

此外/或者,你可以交換的URL定義的順序,因爲Django會採取它匹配的第一個。

+0

謝謝,現在我每次訪問'http://時出現以下錯誤127.0.0.1:8000/api/category/17442811-3217-4b67-8c2c-c4ab762460d6 /':AssertionError at/api/category/17442811-3217-4b67-8c2c-c4ab762460d6 /' – methuselah

+0

我修正了上述錯誤信息這:在'views.py'中http://pastebin.com/MJdKBYsT。它是否正確? – methuselah

+0

我不確定你在問什麼或你做了什麼。 –