Skip to content

Added related fields filtering #504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions rest_framework_json_api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ class RelatedMixin(object):
This mixin handles all related entities, whose Serializers are declared in "related_serializers"
"""

related_filter_backends = {}

def retrieve_related(self, request, *args, **kwargs):
serializer_kwargs = {}
instance = self.get_related_instance()
Expand Down Expand Up @@ -164,13 +166,24 @@ def get_related_instance(self):
field = parent_serializer.fields.get(field_name, None)

if field is not None:
return field.get_attribute(parent_obj)
result = field.get_attribute(parent_obj)
else:
try:
return getattr(parent_obj, field_name)
result = getattr(parent_obj, field_name)
except AttributeError:
raise NotFound

if isinstance(result, QuerySet):
result = self.filter_related_queryset(field_name, result)

return result

def filter_related_queryset(self, field_name, queryset):
backends = self.related_filter_backends.get(field_name, [])
for backend in list(backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset


class ModelViewSet(AutoPrefetchMixin,
PrefetchForIncludesHelperMixin,
Expand Down