为什么URL使用参数pk而不是pk2? [英] Why the url works with parameter pk and not pk2?

查看:38
本文介绍了为什么URL使用参数pk而不是pk2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试发送 pk2 或其他任何参数时,它会引发 AssertionError .我的意思是这个网址

When I try to send pk2 or any other argument, it raises an AssertionError. What I mean is this that the url

path('grade/<str:pk>/', IndividualGrade.as_view(), name="get-grade")

当下面的一个引发错误时,不会引发错误:

doesn't throw an error while the one below causes an error:

path('grade/<str:pk2>/', IndividualGrade.as_view(), name="get-grade")

我的观点非常简单,如下所示:

My view is fairly simple as below:

class IndividualGrade(generics.RetrieveUpdateDestroyAPIView):
    '''    PUT/GET/DELETE grade/{grade:pk}/    '''
    queryset = Grade.objects.all()
    serializer_class = GradeSerializer
    def put(self, request, *args, **kwargs):
        try:
            g1 = Grade.objects.get(grade=kwargs["pk"])
            serializer = GradeSerializer(g1, data=request.data)
            flag = 0
        except Grade.DoesNotExist: # Create a new grade if a grade doesn't exist
            g1 = Grade.objects.get(grade=kwargs["pk"])
            serializer = GradeSerializer(g1, data=request.data)
            flag = 1
        if serializer.is_valid():
            # call update/create here
        else:
            return Response(serializer.errors)
        return Response(serializer.data, status=status.HTTP_200_OK)

如果我编写了自己的get函数(在另一个视图中尝试过),我意识到url中的 pk2 可以工作,但是我不知道如何在不编写自己的get的情况下解决此问题.虽然已经在此处进行了讨论.但是我仍然不确定如何在不编写自己的get的情况下进行修复.

I realized pk2 in the url works if I write my own get function (tried in another view), but I don't know how to fix this without writing my own get. While this have been discussed here. But I am still not sure how to fix it without writing my own get.

推荐答案

您需要添加

lookup_field = 'pk2'

当您使用除pk以外的其他功能时,它是为lookup内置的.当您要在网址中添加其他内容时,您需要提及.

when you are using something else than pk, which is inbuilt for lookup . when you want something else in the url you need to mention that.

这篇关于为什么URL使用参数pk而不是pk2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆