|
1 | 1 | import itertools
|
2 | 2 |
|
3 | 3 | from django.db import models
|
4 |
| -from django_filters import Filter, MultipleChoiceFilter |
| 4 | +from django_filters import Filter, MultipleChoiceFilter, VERSION |
5 | 5 | from django_filters.filterset import BaseFilterSet, FilterSet
|
6 | 6 | from django_filters.filterset import FILTER_FOR_DBFIELD_DEFAULTS
|
7 | 7 |
|
@@ -51,6 +51,37 @@ class GrapheneFilterSetMixin(BaseFilterSet):
|
51 | 51 | )
|
52 | 52 |
|
53 | 53 |
|
| 54 | +# To support a Django 1.11 + Python 2.7 combination django-filter must be |
| 55 | +# < 2.x.x. To support the earlier version of django-filter, the |
| 56 | +# filter_for_reverse_field method must be present on GrapheneFilterSetMixin and |
| 57 | +# must not be present for later versions of django-filter. |
| 58 | +if VERSION[0] < 2: |
| 59 | + from django.utils.text import capfirst |
| 60 | + |
| 61 | + class GrapheneFilterSetMixinPython2(GrapheneFilterSetMixin): |
| 62 | + |
| 63 | + @classmethod |
| 64 | + def filter_for_reverse_field(cls, f, name): |
| 65 | + """Handles retrieving filters for reverse relationships |
| 66 | + We override the default implementation so that we can handle |
| 67 | + Global IDs (the default implementation expects database |
| 68 | + primary keys) |
| 69 | + """ |
| 70 | + try: |
| 71 | + rel = f.field.remote_field |
| 72 | + except AttributeError: |
| 73 | + rel = f.field.rel |
| 74 | + default = {"name": name, "label": capfirst(rel.related_name)} |
| 75 | + if rel.multiple: |
| 76 | + # For to-many relationships |
| 77 | + return GlobalIDMultipleChoiceFilter(**default) |
| 78 | + else: |
| 79 | + # For to-one relationships |
| 80 | + return GlobalIDFilter(**default) |
| 81 | + |
| 82 | + GrapheneFilterSetMixin = GrapheneFilterSetMixinPython2 |
| 83 | + |
| 84 | + |
54 | 85 | def setup_filterset(filterset_class):
|
55 | 86 | """ Wrap a provided filterset in Graphene-specific functionality
|
56 | 87 | """
|
|
0 commit comments