基于id获取Django Rest框架上的单个记录

2024-09-27 21:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我从位于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来访问:

^{pr2}$

但是,当我尝试这样做时,它会返回所有记录。我如何解决这个问题?这是我目前为止的代码:

网址.py

urlpatterns = [
    url(r'^category/', views.CategoryList.as_view(), name="category_list"),
    url(r'^category/?(?P<pk>[^/]+)/$', views.CategoryDetail.as_view(), name="category_detail")
]

视图.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

序列化程序.py

class CategorySerializer(serializers.ModelSerializer):
    """
    Class to serialize Category objects
    """
    class Meta:
        model = Category
        fields = '__all__'
        read_only_fields = ('id')

模型.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)

Tags: pyapiidhttpurltitlemodels记录
1条回答
网友
1楼 · 发布于 2024-09-27 21:30:56

您的第一个正则表达式r'^category/',既匹配有无UUID的URL。在

你应该把它固定在末尾:

r'^category/$'

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

相关问题 更多 >

    热门问题