基于id获取Django Rest Framework的单一记录

时间:2016-05-31 13:34:50

标签: python django rest

我在http://127.0.0.1:8000/api/category/处的REST API中收到以下响应:

[
    {
        "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)

1 个答案:

答案 0 :(得分:2)

您的第一个正则表达式r'^category/'匹配包含和不包含UUID的网址。

你应该把它锚在最后:

r'^category/$'

另外/或者,您可以交换这些URL定义的顺序,因为Django将采用它匹配的第一个。