2016-05-31 123 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

我不确定你在问什么或你做了什么。 –