0

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)

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Banks
  • 179
  • 13

1 Answers1

1

you need to add

lookup_field = 'pk2'

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.

Exprator
  • 26,992
  • 6
  • 47
  • 59
  • Gives me an error `Cannot resolve keyword 'pk2' into field. Choices are: StudentList, id, grade` – Banks Apr 03 '19 at 05:14
  • 1
    ok so you dont have pk2 in the database? then you cant, for that you can only use the fields available in the model – Exprator Apr 03 '19 at 05:16
  • That makes sense. I am assuming it works the same way if there are pk2 and pk3? I just define `lookup_field = 'pk2'`? – Banks Apr 03 '19 at 05:30