34
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Django REST frameworkでフィルターしたいとき

Posted at

今、Django REST frameworkでAPIを作成しているのですが、
日々勉強しつつ作成しているので忘れないようにここに記載します。

■やりたい事
modelでForeignKeyで指定したフィールドをURLで叩く際にID番号ではなく値指定で取得したい!

下記はURLを叩いた際に返ってくるRestの結果。

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.", 
        }
    ]
}

やりたい事の例)
http://127.0.0.1:8000/my_name_rule/1 <-'1'ではなく
http://127.0.0.1:8000/my_name_rule/noge <-'noge'で取得したい


**ここから本題** 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も特に手を加えず。
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')  

そして、views.pyでは、フィルターするクラスの"MyNameRuleFilterViewSet"というクラスを作成
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)

最後にurls.pyでフィルタークラスのurlを指定してあげれば完了。
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'),)

これで出来るはず!
以上っす(`・ω・´)ゞ

34
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?