From d8bdda94dfcf60cf5cf560c32e18305f56d4ddf8 Mon Sep 17 00:00:00 2001 From: Jay Hale Date: Thu, 16 Aug 2018 14:05:34 -0400 Subject: [PATCH] Add back support for django-filter < 2 --- .travis.yml | 2 ++ graphene_django/filter/filterset.py | 33 ++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 4bbbba0..a8375ee 100644 --- a/.travis.yml +++ b/.travis.yml @@ -45,6 +45,8 @@ matrix: env: TEST_TYPE=build DJANGO_VERSION=2.1 - python: '3.6' env: TEST_TYPE=build DJANGO_VERSION=2.1 + - python: '2.7' + env: TEST_TYPE=lint - python: '3.6' env: TEST_TYPE=lint deploy: diff --git a/graphene_django/filter/filterset.py b/graphene_django/filter/filterset.py index 8789147..4059083 100644 --- a/graphene_django/filter/filterset.py +++ b/graphene_django/filter/filterset.py @@ -1,7 +1,7 @@ import itertools from django.db import models -from django_filters import Filter, MultipleChoiceFilter +from django_filters import Filter, MultipleChoiceFilter, VERSION from django_filters.filterset import BaseFilterSet, FilterSet from django_filters.filterset import FILTER_FOR_DBFIELD_DEFAULTS @@ -51,6 +51,37 @@ class GrapheneFilterSetMixin(BaseFilterSet): ) +# To support a Django 1.11 + Python 2.7 combination django-filter must be +# < 2.x.x. To support the earlier version of django-filter, the +# filter_for_reverse_field method must be present on GrapheneFilterSetMixin and +# must not be present for later versions of django-filter. +if VERSION[0] < 2: + from django.utils.text import capfirst + + class GrapheneFilterSetMixinPython2(GrapheneFilterSetMixin): + + @classmethod + def filter_for_reverse_field(cls, f, name): + """Handles retrieving filters for reverse relationships + We override the default implementation so that we can handle + Global IDs (the default implementation expects database + primary keys) + """ + try: + rel = f.field.remote_field + except AttributeError: + rel = f.field.rel + default = {"name": name, "label": capfirst(rel.related_name)} + if rel.multiple: + # For to-many relationships + return GlobalIDMultipleChoiceFilter(**default) + else: + # For to-one relationships + return GlobalIDFilter(**default) + + GrapheneFilterSetMixin = GrapheneFilterSetMixinPython2 + + def setup_filterset(filterset_class): """ Wrap a provided filterset in Graphene-specific functionality """