Django.fun

Filtering data for multiple conditions in DRF

Django newbie here and having a hard time implementing a simple filter operation. I have an Order model which has two fields - order_id and zipcode.

The users are going to pass the above two parameters in the request body and I have to return an order that matches the combination.

API endpoint:

POST https://myapi.com/orders/
{
  "order_id": "A123",
  "zipcode": 10001
}

My solution:

# views.py

from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from rest_framework.viewsets import ViewSet


from ..models import Order
from ..serializers import OrderSerializer


class OrderViewSet(ViewSet):
    def create(self, request):
        queryset = Order.objects.all()
        order = get_object_or_404(
            queryset.filter(order_id=request.data["order_id"]).filter(
                zipcode=request.data["zipcode"]
            )
        )
        serializer = OrderSerializer(order)
        return Response(serializer.data)

Questions

  1. Is ViewSet the right way to go here or should I use generics? Not sure which one to use when.

  2. Is there a better way to apply multiple filters than chaining them like I have done above?

  3. It feels weird to override the create method for a lookup. Is there a better way to do it?

Answers: 1

Answered by starboy_jb, Sept. 14, 2021, 10:15 a.m.

There are multiple ways. Some ways could be like this,

queryset = Order.objects.all()

order_id = request.data["order_id"]
zipcode = request.data["zipcode"]

order = get_object_or_404(
    queryset.filter(order_id=order_id, zipcode=zipcode)
)

or

from django.db.models import Q

order = get_object_or_404(
    queryset.filter(Q(order_id=order_id) & Q(zipcode=zipcode))
)