Skip to content

Remove not always supported auto select_related #651

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

Merged
merged 1 commit into from
Jun 7, 2019
Merged
Show file tree
Hide file tree
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
2 changes: 0 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ any parts of the framework not mentioned in the documentation should generally b
### Changed

* Allow to define `select_related` per include using [select_for_includes](https://django-rest-framework-json-api.readthedocs.io/en/stable/usage.html#performance-improvements)
* Reduce number of queries to calculate includes by using `select_related` when possible
* Use REST framework serializer functionality to extract includes. This adds support like using
dotted notations in source attribute in `ResourceRelatedField`.

Expand All @@ -31,7 +30,6 @@ any parts of the framework not mentioned in the documentation should generally b
### Deprecated

* Deprecate `PrefetchForIncludesHelperMixin` use `PreloadIncludesMixin` instead
* Deprecate `AutoPrefetchMixin` use `AutoPreloadMixin` instead

## [2.7.0] - 2019-01-14

Expand Down
2 changes: 1 addition & 1 deletion example/tests/test_performance.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_query_count_include_author(self):
4. Author types prefetched
5. Entries prefetched
"""
with self.assertNumQueries(4):
with self.assertNumQueries(5):
response = self.client.get('/comments?include=author&page[size]=25')
self.assertEqual(len(response.data['results']), 25)

Expand Down
7 changes: 2 additions & 5 deletions example/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from rest_framework_json_api.filters import OrderingFilter, QueryParameterValidationFilter
from rest_framework_json_api.pagination import JsonApiPageNumberPagination
from rest_framework_json_api.utils import format_drf_errors
from rest_framework_json_api.views import ModelViewSet, PreloadIncludesMixin, RelationshipView
from rest_framework_json_api.views import ModelViewSet, RelationshipView

from example.models import Author, Blog, Comment, Company, Entry, Project, ProjectType
from example.serializers import (
Expand Down Expand Up @@ -200,12 +200,9 @@ def get_queryset(self, *args, **kwargs):
return super(CommentViewSet, self).get_queryset()


class CompanyViewset(PreloadIncludesMixin, viewsets.ModelViewSet):
class CompanyViewset(ModelViewSet):
queryset = Company.objects.all()
serializer_class = CompanySerializer
prefetch_for_includes = {
'current_project': ['current_project'],
}


class ProjectViewset(ModelViewSet):
Expand Down
32 changes: 6 additions & 26 deletions rest_framework_json_api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,20 +115,18 @@ def get_queryset(self, *args, **kwargs):
return qs


class AutoPreloadMixin(object):

class AutoPrefetchMixin(object):
def get_queryset(self, *args, **kwargs):
""" This mixin adds automatic prefetching for OneToOne and ManyToMany fields. """
qs = super(AutoPreloadMixin, self).get_queryset(*args, **kwargs)
qs = super(AutoPrefetchMixin, self).get_queryset(*args, **kwargs)

included_resources = get_included_resources(self.request)

for included in included_resources + ['__all__']:
# If include was not defined, trying to resolve it automatically
included_model = None
levels = included.split('.')
level_model = qs.model
# Suppose we can do select_related by default
can_select_related = True
for level in levels:
if not hasattr(level_model, level):
break
Expand All @@ -144,12 +142,6 @@ def get_queryset(self, *args, **kwargs):
if not (is_forward_relation or is_reverse_relation):
break

# Figuring out if relation should be select related rather than prefetch_related
# If at least one relation in the chain is not "selectable" then use "prefetch"
can_select_related &= (
issubclass(field_class, (ForwardManyToOneDescriptor, ReverseOneToOneDescriptor))
)

if level == levels[-1]:
included_model = field
else:
Expand All @@ -165,23 +157,11 @@ def get_queryset(self, *args, **kwargs):
level_model = model_field.model

if included_model is not None:
if can_select_related:
qs = qs.select_related(included.replace('.', '__'))
else:
qs = qs.prefetch_related(included.replace('.', '__'))
qs = qs.prefetch_related(included.replace('.', '__'))

return qs


class AutoPrefetchMixin(AutoPreloadMixin):

def __init__(self, *args, **kwargs):
warnings.warn("AutoPrefetchMixin is deprecated. "
"Use AutoPreloadMixin instead",
DeprecationWarning)
super(AutoPrefetchMixin, self).__init__(*args, **kwargs)


class RelatedMixin(object):
"""
This mixin handles all related entities, whose Serializers are declared in "related_serializers"
Expand Down Expand Up @@ -259,14 +239,14 @@ def get_related_instance(self):
raise NotFound


class ModelViewSet(AutoPreloadMixin,
class ModelViewSet(AutoPrefetchMixin,
PreloadIncludesMixin,
RelatedMixin,
viewsets.ModelViewSet):
pass


class ReadOnlyModelViewSet(AutoPreloadMixin,
class ReadOnlyModelViewSet(AutoPrefetchMixin,
RelatedMixin,
viewsets.ReadOnlyModelViewSet):
pass
Expand Down