LoginSignup
2
1

More than 5 years have passed since last update.

graphene-djangoでソートする

Last updated at Posted at 2018-05-26

graphene-djangoでクエリ投げる時にソート(order by)したい。

動作環境

  • Python3
  • django 2.0.1
  • graphene-django 2.0.0
  • django-filter 1.1.0

コード

基本方針は django_filters.FilterSet を継承したカスタムフィルターを実装し、order by可能なフィールドを定義すること。 order by可能なフィールドの定義には、django_filters.OrderingFilterを使う。

models.py
from django.db import models

## 対象のモデル. なんでも大丈夫
class Articles(models.Model):
    created_at = models.DateTimeField()
    title = models.CharField(max_length=128, blank=True, null=True)
    content = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'articles'
schema.py
from graphene import Schema, ObjectType, Node
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField

from django_filters import FilterSet, OrderingFilter

from . import models

## カスタムフィルター
class ArticleFilter(FilterSet):

    class Meta:
        model = models.Tags
        fields = {
            "title":["icontains"],
            "content":["icontains"],
            "created_at":["gte", "lte"], 
        }

    # order byの定義
    order_by = OrderingFilter(
        fields = (
            #1つ目のcreated_atはmodels.Tagで定義されたfield名
            #2つ目のcreated_atはクエリでorderby指定する時のパラメータ名
            #今回は同じ名前にする
            ("created_at", "created_at"),
        )
    )

class Article(DjangoObjectType):
    class Meta:
        model = models.Articles
        interfaces = (Node, )

class Query(ObjectType):
    article =  Node.Field(Article)
    # 上で定義したカスタムフィルターを指定する
    all_articles = DjangoFilterConnectionField(Article,
        filterset_class=ArticleFilter)

schema = Schema(query=Query)

クエリ例

ソートに使うフィールドをorderByで指定する。フィールド名の前に-を付けると、降順ソートとなる。
下記クエリで、作成日時(created_at)が新しいもの100件のリストが返される。

query {
  allArticles(first: 100, orderBy:"-created_at") {
    edges {
      node {
        title
        content
        created_at
      }
    }
  }
}
2
1
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
2
1