Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Django Rest框架中通过URL中的pk获取对象_Django_Django Rest Framework - Fatal编程技术网

在Django Rest框架中通过URL中的pk获取对象

在Django Rest框架中通过URL中的pk获取对象,django,django-rest-framework,Django,Django Rest Framework,我想通过URL中的“pk”从ORM检索对象。 这是我正在尝试的 这是我的网址: path('api/dispatchhistoryitem/<int:pk>/', views.dispatchhistoryitemsview.as_view(), 'dispatchhistoryitem'), 序列化程序.py class holdSerializer(serializers.ModelSerializer): class Meta: model = Ite

我想通过URL中的“pk”从ORM检索对象。 这是我正在尝试的

这是我的网址:

path('api/dispatchhistoryitem/<int:pk>/', views.dispatchhistoryitemsview.as_view(), 'dispatchhistoryitem'),
序列化程序.py

class holdSerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemBatch
        fields = "__all__"
但当我运行这个时,它会说:

/api/dispatchhistoryitem/43处的值错误/

字典更新序列元素#0的长度为1;2是必需的


我做错了什么?请帮忙

我认为本质上问题在于你使用了错误的观点。
ListAPIView
用于检索对象列表

您可以在这里使用已经实现了样板逻辑的。如果您的URL包含一个
pk
参数,它可以自动过滤该
pk
,因此无需自行实现此逻辑:

from rest_framework.generics import RetrieveAPIView

class dispatchhistoryitemsview(RetrieveAPIView):
    queryset = ItemBatch.objects.all()
    serializer_class = holdSerializer
来自rest\u framework.generics导入retrieveapiew
类dispatchhistoryitemsview(RetrieveAppView):
queryset=ItemBatch.objects.all()
serializer\u class=holdSerializer
此外,由于第三个参数是kwargs,因此应使用命名参数:

path(
    'api/dispatchhistoryitem/<int:pk>/',
    views.dispatchhistoryitemsview.as_view(),
    name='dispatchhistoryitem'
),
路径(
“api/dispatchhistoryitem/”,
views.dispatchhistoryitemsview.as_view(),
name='dispatchhistoryitem'

),
这个答案可能会有所帮助:我不明白如果您想获取单个项目,为什么要使用ListView。使用DetailView,则根本不需要定义
get
。这很有意义,但在路径中添加“name=”解决了ruddra在中所述的问题comments@RahulSharma:啊,是的,但这意味着你在某处有一个
{%url…%}
反向(…)
重定向(…)
(这不是你的问题)转到
dispatchhistoryitem
视图。
path(
    'api/dispatchhistoryitem/<int:pk>/',
    views.dispatchhistoryitemsview.as_view(),
    name='dispatchhistoryitem'
),