Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.1K
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!