Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.1K
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda