Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.1K
Visualizações
How to properly override get_queryset in a modelviewset without breaking the query by pk?

I have a ModelViewSet:

class OrderViewSet(viewsets.ModelViewSet):
serializer_class = OrderSerializer
pagination_class = DefaultPagination
queryset = Order.objects.all()

def get_queryset(self):
    userId = self.request.query_params.get('userId')
    if userId is not None:
        query = Order.objects.filter(owner__id=userId).order_by('-createdAt')
    else:
        query = Order.objects.order_by('-createdAt')
    return query

Here is the url registration

router = routers.DefaultRouter()
router.register('api/v1/order', OrderViewSet, basename='order')

I found that after overriding the get_queryset, I can no longer query by one order id like the following anymore: /api/v1/order/1,it just returns detail: not found

I do see django saying it supports:

^api/v1/order/$ [name='order-list']
^api/v1/order\.(?P<format>[a-z0-9]+)/?$ [name='order-list']
^api/v1/order/(?P<pk>[^/.]+)/$ [name='order-detail']
^api/v1/order/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='order-detail']

what should be the correct way to do this? Thanks!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

To fix this, call super() when overriding the get_queryset()

Give this a try

def get_queryset(self):
    queryset = super(OrderViewSet, self).get_queryset()

    userId = self.request.query_params.get('userId')
    if userId is not None:
         queryset = queryset.filter(owner__id=userId).order_by('-createdAt')
    else:
        queryset = queryset.order_by('-createdAt')
    return query
over 4 years ago · Santiago Trujillo Relatório

0

What about using Django's function-based views and class-based to your advantage. I can think of a solution where you can create another function based view to handle the above functionality and let the class based view get method handle the pk query set.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda