Django Rest: A simple filtering view with arguments

You have a Model. You want to sort its instances by a parameter. This parameter should be passed in the url. Here you go.

It is pretty much from docs, I just didn’t find it fast enough in the first time, so I decided to post about it.

urls.py

from django.urls import path
from rest_framework import serializers, generics
from .models import Vibe


class VibeColorView(generics.ListAPIView):
    serializer_class = VibeSerializer  # anything you want for your model

    def get_queryset(self):
        color = str(self.kwargs['color']).lower().title()
        return Vibe.objects.filter(color=color)


class VibeMoodView(generics.ListAPIView):
    serializer_class = VibeSerializer  # anything you want for your model

    def get_queryset(self):
        mood = str(self.kwargs['mood']).lower().title()
        return Vibe.objects.filter(mood=mood)


urlpatterns = [
    path('vibe/color/<str:color>/', VibeColorView.as_view()),
    path('vibe/mood/<str:mood>/', VibeMoodView.as_view()),
]

models.py

class Vibe(models.Model):
    COLOR_OPTIONS = (
      ('Red', 'red'),
      ('Lavender', 'lavender'),
      ('Blue', 'blue'),
    )

    MOOD_OPTIONS = (
      ('Happy', 'happy'),
      ('Angry', 'angry'),
      ('Sad', 'sad'),
    )
    name = models.Charfield(max_length=100)
    color = models.Charfield(choices=COLOR_OPTIONS, max_length=100)
    mood = models.Charfield(choices=MOOD_OPTIONS, max_length=100)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.