Alias unified job template search fields for presentation

The polymorphic accessors have a name that is different than our
normal presentation name for these types. This aliases them for the
presentation layer and then handles processing them when they are
given as filters.
This commit is contained in:
Matthew Jones 2017-02-22 15:33:47 -05:00
parent a484dae41a
commit b14336bdff
3 changed files with 22 additions and 2 deletions

View File

@ -112,7 +112,13 @@ class FieldLookupBackend(BaseFilterBackend):
elif name == 'pk':
field = model._meta.pk
else:
field = model._meta.get_field_by_name(name)[0]
name_alt = name.replace("_", "")
if name_alt in model._meta.fields_map.keys():
field = model._meta.fields_map[name_alt]
new_parts.pop()
new_parts.append(name_alt)
else:
field = model._meta.get_field_by_name(name)[0]
if isinstance(field, ForeignObjectRel) and getattr(field.field, '__prevent_search__', False):
raise PermissionDenied(_('Filtering on %s is not allowed.' % name))
elif getattr(field, '__prevent_search__', False):

View File

@ -9,6 +9,7 @@ import time
# Django
from django.conf import settings
from django.db import connection
from django.db.models.fields import FieldDoesNotExist
from django.http import QueryDict
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
@ -285,7 +286,7 @@ class ListAPIView(generics.ListAPIView, GenericAPIView):
if getattr(field, 'related_model', None):
fields.append('{}__search'.format(field.name))
for rel in self.model._meta.related_objects:
name = rel.get_accessor_name()
name = rel.related_model._meta.verbose_name.replace(" ", "_")
if name is None:
continue
if name.endswith('_set'):
@ -308,6 +309,8 @@ class ListAPIView(generics.ListAPIView, GenericAPIView):
FieldLookupBackend().get_field_from_lookup(self.model, field)
except PermissionDenied:
pass
except FieldDoesNotExist:
allowed_fields.append(field)
else:
allowed_fields.append(field)
return allowed_fields

View File

@ -0,0 +1,11 @@
import pytest
from django.core.urlresolvers import reverse
@pytest.mark.django_db
def test_aliased_forward_reverse_field_searches(instance, options, get, admin):
url = reverse('api:unified_job_template_list')
response = options(url, None, admin)
assert 'job_template__search' in response.data['related_search_fields']
get(reverse("api:unified_job_template_list") + "?job_template__search=anything", user=admin, expect=200)