When you want to filter with Django REST framework

I'm currently creating an API with the Django REST framework. I am creating it while studying every day, so I will write it here so that I do not forget it.

■ What you want to do When hitting the field specified by Foreign Key in model with URL, I want to get it by specifying the value instead of the ID number!

Below is the result of Rest that is returned when you hit the URL.

python


URL:http://127.0.0.1:8000/my_names
{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "my_name": "noge", 
        }
    ]
}
URL:http://127.0.0.1:8000/my_name_rules

{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "my_name": "1", 
            "my_name_rule": "noge is rule.", 
        }
    ]
}

Example of what you want to do) http://127.0.0.1:8000/my_name_rule/1 <-not '1' I want to get it with http://127.0.0.1:8000/my_name_rule/noge <-'noge'


** Main subject from here ** No particular modification to models.py.

models.py


from django.db import models 

class MyName(models.Model):
    my_name = models.CharField(max_length=255, unique=True)

    def __unicode__(self):
        return self.my_name       

    class Meta(object):
        db_table = 'my_name'      


class MyNameRule(models.Model):
    my_name = models.ForeignKey(MyName)
    my_name_rule = models.CharField(max_length=255)
                                                                                                                                                                                                                                                                              
    def __unicode__(self):
        return self.my_name_rule       

    class Meta(object):
        db_table = 'my_name_rule'     

serializers.py is also untouched.

serializers.py


from rest_framework import serializers
from noge.apps.noge.models import MyName
from noge.apps.noge.models import MyNameRule

class MyNameRuleSerializer(serializers.ModelSerializer):

    class Meta(object):
        model = MyNameRule
        fields = ('my_name', 'my_name_rule')

class MyNameSerializer(serializers.ModelSerializer):

    class Meta(object):
        model = MyName
        fields = ('my_name')  

And in views.py, create a class called "MyNameRuleFilterViewSet" for the filtering class.

views.py



from rest_framework import viewsets
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
from noge.apps.noge.models import MyName
from noge.apps.noge.models import MyNameRule
from noge.apps.noge.serializers import MyNameSerializer
from noge.apps.noge.serializers import MyNameRuleSerializer

class MyNameViewSet(viewsets.ModelViewSet):
    queryset = MyName.objects.all()
    serializer_class = MyNameSerializer
    permission_classes = (IsAuthenticated,)

class MyNameRuleViewSet(viewsets.ModelViewSet):
    queryset = MyNameRule.objects.all()
    serializer_class = MyNameRuleSerializer
    permission_classes = (IsAuthenticated,)

class MyNameRuleFilterViewSet(generics.ListAPIView):
    serializer_class = MyNameRuleSerializer
    def get_queryset(self):
        query_my_name = self.kwargs['my_name']
        return MyNameRule.objects.filter(my_name__my_name=query_my_name)

Finally, specify the url of the filter class in urls.py and you're done.

urls.py


from rest_framework import routers
from noge.apps.noge import views
from noge.apps.noge.views import MyNameRuleFilterViewSet

router = routers.DefaultRouter(trailing_slash=False)
router.register(r'my_names', views.MyNameViewSet)
router.register(r'my_name_rules', views.MyNameRuleViewSet)

urlpatterns = patterns('noge.apps.noge.views',
                       url(r'^v1/my_name_rules/(?P<my_name>\w+)/$',MyNameRuleFilterViewSet.as_view()),
                       url(r'^v1/', include(router.urls)),
                       url(r'^$', 'index', name='index'),)

You should be able to do this! That's it (`・ ω ・ ´) ゞ

Recommended Posts

When you want to filter with Django REST framework
Sometimes you want to access View information from Serializer with DRF (Django REST Framework)
Django REST framework with Vue.js
Login with django rest framework
Settings when you want to run python-mecab with travis
Things to do when you start developing with Django
[Django] Use MessagePack with Django REST framework
Solution when you want to use cv_bridge with python3 (virtualenv)
[Django] A memorandum when you want to communicate asynchronously [Python3]
[AWS] What to do when you want to pip with Lambda
Use aggdraw when you want to draw beautifully with pillow
When you want to register Django's initial data with relationships
Create RESTful APIs with Django Rest Framework
CRUD GET with Nuxt & Django REST Framework ②
When you want to print to standard output with print while testing with pytest
CRUD POST with Nuxt & Django REST Framework
CRUD GET with Nuxt & Django REST Framework ①
When you want to send an object with requests using flask
Create a REST API to operate dynamodb with the Django REST Framework
When you want to adjust the axis scale interval with APLpy
Gist repository to use when you want to try a little with ansible
When you want to replace a column with a missing value (NaN) column by column
Memorandum of means when you want to make machine learning with 50 images
How to deal with garbled characters in json of Django REST Framework
CRUD PUT, DELETE with Nuxt & Django REST Framework
When you want to update the chrome driver.
Django REST framework A little useful to know.
Implementing authentication in Django REST Framework with djoser
Django REST framework basics
Django Rest Framework Tips
AssertNumQueries is useful if you want to easily test N + 1 queries with django
Personal best practice template to use when you want to make MVP with Flask
How to automatically generate API document with Django REST framework & POST from document screen
[OpenCV] When you want to check if it is read properly with imread
If you want to make a discord bot with python, let's use a framework
Create a Todo app with Django REST Framework + Angular
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
More new user authentication methods with Django REST Framework
Create a Todo app with the Django REST framework
Create APIs around user authentication with Django REST Framework
Links to do what you want with Sublime Text
When you want to play a game via Proxy
[Django Rest Framework] Customize the filter function using Django-Filter
When you want to plt.save in a for statement
Things to watch out for when migrating with Django
Implement hierarchical URLs with drf-nested-routers in Django REST framework
When the variable you want to superscript with matplotlib is two or more characters
Django REST framework stumbling block
How to handle static files when deploying to production with Django
Eliminate errors that occur when using Django REST Swagger with Django 3.0
Knowledge you need to know when programming competitive programming with Python2
The first API to make with python Djnago REST framework
How to reset password via API using Django rest framework
I want to make a blog editor with django admin
How to resolve CSRF Protection when using AngularJS with Django
When you want to use python2.x on modern Gentoo Linux
When you want to hit a UNIX command on Python
I know? Data analysis using Python or things you want to use when you want with numpy
Useful operation when you want to solve all problems in multiple programming languages with Codewars
If you want to use field names with hyphens when updating firestore data in python
[Subprocess] When you want to execute another Python program in Python code