Задать вопрос
@robocop45

KeyError at /api/questapp/quests/1/categories/2/cards/1/ 'category_id', как правильно реализовать маршрут?

нужно реализовать эндпоинт GET /quests/{id}/categories/{id}/cards/{id}, а именно /cards/{id},
вроде все сделал, но появляется ошибка
KeyError at /api/questapp/quests/1/categories/2/cards/1/
'category_id'


views
class AssignmentAPI(viewsets.ReadOnlyModelViewSet):
    permission_classes = [permissions.AllowAny]
    serializer_class = QuestCategoriesCardsSerializer

    def get_queryset(self):
        category_id = self.kwargs['category_id']
        return Assignment.objects.filter(category_id=category_id)

    @action(detail=True, methods=['get'])
    def cards(self, request, *args, **kwargs):
        card_id = self.kwargs['pk']
        queryset = self.get_queryset().filter(id=card_id)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


serializer

class QuestCategoriesCardsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Assignment
        fields = (
            'category',
            'answer_type',
            'picture',
            'question',
            'answer',
            'is_enumeration',
            'enumeration_sep',
            'skip_symbols'
        )


urls
router = routers.SimpleRouter()
router.register(r'quests', QuestAPI)

quest_category_router = routers.NestedSimpleRouter(router, r'quests', lookup='quest')
quest_category_router.register(r'categories', CategoryAPI, basename='quest-categories')

quest_category_card_router = routers.NestedSimpleRouter(quest_category_router, r'categories', lookup='category_id')
quest_category_card_router.register(r'cards', AssignmentAPI, basename='quest-category-cards')


urlpatterns = [
    path('', include(router.urls)),
    path('', include(quest_category_router.urls)),
    path('', include(quest_category_card_router.urls)),

]


Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 56, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 55, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/mixins.py", line 54, in retrieve
    instance = self.get_object()
  File "/usr/local/lib/python3.9/site-packages/rest_framework/generics.py", line 83, in get_object
    queryset = self.filter_queryset(self.get_queryset())
  File "/usr/src/app/my_city/quest_app/views.py", line 54, in get_queryset
    category_id = self.kwargs['category_id']

Exception Type: KeyError at /api/questapp/quests/1/categories/2/cards/1/
Exception Value: 'category_id'
  • Вопрос задан
  • 164 просмотра
Подписаться 1 Простой 8 комментариев
Пригласить эксперта
Ответы на вопрос 1
@robocop45 Автор вопроса
def get_queryset(self):
        category_id = self.kwargs.get('category_id')
        return Assignment.objects.filter(category_id=category_id)


изменил код и ошибка пропала
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы