4
2

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.

graphene-djangoで範囲指定検索する

Posted at

背景

graphene-djangoで範囲指定検索したい。あまり日付指定に関するメモを見なかったので残しておく。

動作環境

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

コード

基本方針は django_filterを使って、gte, lteを指定するだけ。

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 . import models

class Article(DjangoObjectType):
    class Meta:
        model = models.Articles
        interfaces = (Node, )
        filter_fields = {
            "title": ["icontains"],
            "content": ["icontains"],
            # ここで"gte"と"lte"を指定するだけ
            "created_at": ["gte", "lte"]
        }

class Query(ObjectType):
    article =  Node.Field(Article)
    all_articles = DjangoFilterConnectionField(Article)

schema = Schema(query=Query)

クエリ例

createdAt_GtecreatedAt_Lteを指定すれば範囲検索ができる。
両方指定するとAnd条件、片方だけ指定することもできる。

# 2018年2月の全Articleを取得する例
query {
  allArticles(createdAt_Gte:"2018-02-01", createdAt_Lte:"2018-02-28) {
    edges {
      node {
        title
        content
        created_at
      }
    }
  }
}
# 2月1日10時〜18時までのArticleを取得する例
query {
  allArticles(createdAt_Gte:"2018-02-01 10:00:00", createdAt_Lte:"2018-02-01 18:00:00) {
    edges {
      node {
        title
        content
        created_at
      }
    }
  }
}
# 2018年より前の全Articleを取得する例
query {
  allArticles(createdAt_Lte:"2017-12-31 23:59:59) {
    edges {
      node {
        title
        content
        created_at
      }
    }
  }
}
4
2
1

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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?