From 4de86b4521ae0d1c0c752fc919957e634b9ba5cc Mon Sep 17 00:00:00 2001 From: Oliver Sauder Date: Sun, 11 Aug 2019 17:27:22 +0200 Subject: [PATCH] Remove all deprecated code Fixes #662 --- CHANGELOG.md | 8 ++ example/api/resources/identity.py | 4 +- example/tests/test_multiple_id_mixin.py | 82 ------------------ example/tests/test_parsers.py | 12 --- .../unit/test_default_drf_serializers.py | 11 --- example/tests/unit/test_pagination.py | 71 ---------------- example/tests/unit/test_renderers.py | 11 --- example/tests/unit/test_utils.py | 24 ------ pytest.ini | 2 - rest_framework_json_api/mixins.py | 38 --------- rest_framework_json_api/pagination.py | 63 -------------- rest_framework_json_api/parsers.py | 8 +- rest_framework_json_api/renderers.py | 14 +-- rest_framework_json_api/settings.py | 12 --- rest_framework_json_api/utils.py | 85 +------------------ rest_framework_json_api/views.py | 40 --------- 16 files changed, 22 insertions(+), 463 deletions(-) delete mode 100644 example/tests/test_multiple_id_mixin.py delete mode 100644 rest_framework_json_api/mixins.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ad1ecbe6..e43e850d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ any parts of the framework not mentioned in the documentation should generally b ## [Unreleased] +This release is not backwards compatible. For easy migration best upgrade first to version +2.8.0 and resolve all deprecation warnings before updating to 3.0.0 + ### Added * Add support for Django REST framework 3.10. @@ -21,6 +24,11 @@ any parts of the framework not mentioned in the documentation should generally b * Removed obsolete dependency six. * Removed support for Django REST Framework <=3.8. * Removed support for Django 2.0. +* Removed obsolete mixins `MultipleIDMixin` and `PrefetchForIncludesHelperMixin` +* Removed obsolete settings `JSON_API_FORMAT_KEYS`, `JSON_API_FORMAT_RELATION_KEYS` and + `JSON_API_PLURALIZE_RELATION_TYPE` +* Removed obsolete util methods `format_keys` and `format_relation_name` +* Removed obsolete pagination classes `PageNumberPagination` and `LimitOffsetPagination` ### Fixed diff --git a/example/api/resources/identity.py b/example/api/resources/identity.py index 09cb3b38..61973845 100644 --- a/example/api/resources/identity.py +++ b/example/api/resources/identity.py @@ -4,13 +4,13 @@ from rest_framework.decorators import action from rest_framework.response import Response -from rest_framework_json_api import mixins, utils +from rest_framework_json_api import utils from ..serializers.identity import IdentitySerializer from ..serializers.post import PostSerializer -class Identity(mixins.MultipleIDMixin, viewsets.ModelViewSet): +class Identity(viewsets.ModelViewSet): queryset = auth_models.User.objects.all().order_by('pk') serializer_class = IdentitySerializer diff --git a/example/tests/test_multiple_id_mixin.py b/example/tests/test_multiple_id_mixin.py deleted file mode 100644 index ac21b2e5..00000000 --- a/example/tests/test_multiple_id_mixin.py +++ /dev/null @@ -1,82 +0,0 @@ -import json - -from django.urls import reverse -from django.utils import encoding - -from example.tests import TestBase - - -class MultipleIDMixin(TestBase): - """ - Test usage with MultipleIDMixin - - [, - [^/]+)/$>] - """ - list_url = reverse('user-list') - - def test_single_id_in_query_params(self): - """ - Ensure single ID in query params returns correct result - """ - url = '/identities?ids[]={0}'.format(self.miles.pk) - response = self.client.get(url) - self.assertEqual(response.status_code, 200) - - expected = { - 'data': { - 'type': 'users', - 'id': encoding.force_text(self.miles.pk), - 'attributes': { - 'first_name': self.miles.first_name, - 'last_name': self.miles.last_name, - 'email': self.miles.email - } - } - } - - json_content = json.loads(response.content.decode('utf8')) - links = json_content.get("links") - meta = json_content.get("meta").get('pagination') - - self.assertEqual(expected.get('user'), json_content.get('user')) - self.assertEqual(meta.get('count', 0), 1) - self.assertEqual(links.get("next"), None) - self.assertEqual(meta.get("page"), 1) - - def test_multiple_ids_in_query_params(self): - """ - Ensure multiple IDs in query params return correct result - """ - url = '/identities?ids[]={0}&ids[]={1}'.format( - self.miles.pk, self.john.pk) - response = self.client.get(url) - self.assertEqual(response.status_code, 200) - - expected = { - 'data': { - 'type': 'users', - 'id': encoding.force_text(self.john.pk), - 'attributes': { - 'first_name': self.john.first_name, - 'last_name': self.john.last_name, - 'email': self.john.email - } - } - } - - json_content = json.loads(response.content.decode('utf8')) - links = json_content.get("links") - meta = json_content.get("meta").get('pagination') - - self.assertEqual(expected.get('user'), json_content.get('user')) - self.assertEqual(meta.get('count', 0), 2) - self.assertEqual( - sorted( - 'http://testserver/identities?ids%5B%5D=2&ids%5B%5D=1&page%5Bnumber%5D=2' - .split('?')[1].split('&') - ), - sorted( - links.get("next").split('?')[1].split('&')) - ) - self.assertEqual(meta.get("page"), 1) diff --git a/example/tests/test_parsers.py b/example/tests/test_parsers.py index 6c4d7252..41ad05ac 100644 --- a/example/tests/test_parsers.py +++ b/example/tests/test_parsers.py @@ -1,7 +1,6 @@ import json from io import BytesIO -import pytest from django.test import TestCase, override_settings from rest_framework.exceptions import ParseError @@ -35,17 +34,6 @@ def __init__(self): self.string = json.dumps(data) - @pytest.mark.filterwarnings("ignore:`format_keys` function and `JSON_API_FORMAT_KEYS`") - @override_settings(JSON_API_FORMAT_KEYS='camelize') - def test_parse_include_metadata_format_keys(self): - parser = JSONParser() - - stream = BytesIO(self.string.encode('utf-8')) - data = parser.parse(stream, None, self.parser_context) - - self.assertEqual(data['_meta'], {'random_key': 'random_value'}) - self.assertEqual(data['json_value'], {'json_key': 'JsonValue'}) - @override_settings(JSON_API_FORMAT_FIELD_NAMES='dasherize') def test_parse_include_metadata_format_field_names(self): parser = JSONParser() diff --git a/example/tests/unit/test_default_drf_serializers.py b/example/tests/unit/test_default_drf_serializers.py index 1fa74565..680f6a8a 100644 --- a/example/tests/unit/test_default_drf_serializers.py +++ b/example/tests/unit/test_default_drf_serializers.py @@ -69,17 +69,6 @@ def test_render_format_field_names(settings): assert result['data']['attributes']['json-field'] == {'JsonKey': 'JsonValue'} -@pytest.mark.filterwarnings("ignore:`format_keys` function and `JSON_API_FORMAT_KEYS`") -def test_render_format_keys(settings): - """Test that json field value keys are formated.""" - delattr(settings, 'JSON_API_FORMAT_FILED_NAMES') - settings.JSON_API_FORMAT_KEYS = 'dasherize' - rendered = render_dummy_test_serialized_view(DummyTestViewSet) - - result = json.loads(rendered.decode()) - assert result['data']['attributes']['json-field'] == {'json-key': 'JsonValue'} - - @pytest.mark.django_db def test_blog_create(client): diff --git a/example/tests/unit/test_pagination.py b/example/tests/unit/test_pagination.py index 9da8675f..aeb5f87e 100644 --- a/example/tests/unit/test_pagination.py +++ b/example/tests/unit/test_pagination.py @@ -1,7 +1,5 @@ -import sys from collections import OrderedDict -import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.utils.urls import replace_query_param @@ -78,72 +76,3 @@ def test_valid_offset_limit(self): assert queryset == list(range(offset + 1, next_offset + 1)) assert content == expected_content - - @pytest.mark.xfail((sys.version_info.major, sys.version_info.minor) == (2, 7), - reason="python2.7 fails to generate DeprecationWarrning for unknown reason") - def test_limit_offset_deprecation(self): - with pytest.warns(DeprecationWarning) as record: - pagination.LimitOffsetPagination() - assert len(record) == 1 - assert 'LimitOffsetPagination is deprecated' in str(record[0].message) - - class MyInheritedLimitOffsetPagination(pagination.LimitOffsetPagination): - """ - Inherit the default values - """ - pass - - class MyOverridenLimitOffsetPagination(pagination.LimitOffsetPagination): - """ - Explicitly set max_limit to the "old" values. - """ - max_limit = None - - def test_my_limit_offset_deprecation(self): - with pytest.warns(DeprecationWarning) as record: - self.MyInheritedLimitOffsetPagination() - assert len(record) == 1 - assert 'LimitOffsetPagination is deprecated' in str(record[0].message) - - with pytest.warns(None) as record: - self.MyOverridenLimitOffsetPagination() - assert len(record) == 0 - - -class TestPageNumber: - """ - Unit tests for `pagination.JsonApiPageNumberPagination`. - """ - - @pytest.mark.xfail((sys.version_info.major, sys.version_info.minor) == (2, 7), - reason="python2.7 fails to generate DeprecationWarrning for unknown reason") - def test_page_number_deprecation(self): - with pytest.warns(DeprecationWarning) as record: - pagination.PageNumberPagination() - assert len(record) == 1 - assert 'PageNumberPagination is deprecated' in str(record[0].message) - - class MyInheritedPageNumberPagination(pagination.PageNumberPagination): - """ - Inherit the default values - """ - pass - - class MyOverridenPageNumberPagination(pagination.PageNumberPagination): - """ - Explicitly set page_query_param and page_size_query_param to the "old" values. - """ - page_query_param = "page" - page_size_query_param = "page_size" - - @pytest.mark.xfail((sys.version_info.major, sys.version_info.minor) == (2, 7), - reason="python2.7 fails to generate DeprecationWarrning for unknown reason") - def test_my_page_number_deprecation(self): - with pytest.warns(DeprecationWarning) as record: - self.MyInheritedPageNumberPagination() - assert len(record) == 1 - assert 'PageNumberPagination is deprecated' in str(record[0].message) - - with pytest.warns(None) as record: - self.MyOverridenPageNumberPagination() - assert len(record) == 0 diff --git a/example/tests/unit/test_renderers.py b/example/tests/unit/test_renderers.py index 1452aac8..e432704d 100644 --- a/example/tests/unit/test_renderers.py +++ b/example/tests/unit/test_renderers.py @@ -83,17 +83,6 @@ def test_render_format_field_names(settings): assert result['data']['attributes']['json-field'] == {'JsonKey': 'JsonValue'} -@pytest.mark.filterwarnings("ignore:`format_keys` function and `JSON_API_FORMAT_KEYS`") -def test_render_format_keys(settings): - """Test that json field value keys are formated.""" - delattr(settings, 'JSON_API_FORMAT_FILED_NAMES') - settings.JSON_API_FORMAT_KEYS = 'dasherize' - rendered = render_dummy_test_serialized_view(DummyTestViewSet, Entry()) - - result = json.loads(rendered.decode()) - assert result['data']['attributes']['json-field'] == {'json-key': 'JsonValue'} - - def test_writeonly_not_in_response(): """Test that writeonly fields are not shown in list response""" diff --git a/example/tests/unit/test_utils.py b/example/tests/unit/test_utils.py index 73c2e650..f2822f2b 100644 --- a/example/tests/unit/test_utils.py +++ b/example/tests/unit/test_utils.py @@ -61,30 +61,6 @@ def test_get_resource_name(): assert 'users' == utils.get_resource_name(context), 'derived from non-model serializer' -@pytest.mark.filterwarnings("ignore:`format_keys` function and `JSON_API_FORMAT_KEYS`") -def test_format_keys(): - underscored = { - 'first_name': 'a', - 'last_name': 'b', - } - - output = {'firstName': 'a', 'lastName': 'b'} - result = pytest.deprecated_call(utils.format_keys, underscored, 'camelize') - assert result == output - - output = {'FirstName': 'a', 'LastName': 'b'} - assert utils.format_keys(underscored, 'capitalize') == output - - output = {'first-name': 'a', 'last-name': 'b'} - assert utils.format_keys(underscored, 'dasherize') == output - - new_input = {'firstName': 'a', 'lastName': 'b'} - assert utils.format_keys(new_input, 'underscore') == underscored - - output = [{'first-name': 'a', 'last-name': 'b'}] - assert utils.format_keys([underscored], 'dasherize') == output - - @pytest.mark.parametrize("format_type,output", [ ('camelize', {'fullName': {'last-name': 'a', 'first-name': 'b'}}), ('capitalize', {'FullName': {'last-name': 'a', 'first-name': 'b'}}), diff --git a/pytest.ini b/pytest.ini index 85da3c71..2c69372d 100644 --- a/pytest.ini +++ b/pytest.ini @@ -3,5 +3,3 @@ DJANGO_SETTINGS_MODULE=example.settings.test filterwarnings = error::DeprecationWarning error::PendingDeprecationWarning - # TODO: restructure tests so this can be ignored on a test level - ignore:MultipleIDMixin is deprecated diff --git a/rest_framework_json_api/mixins.py b/rest_framework_json_api/mixins.py deleted file mode 100644 index fd4219ca..00000000 --- a/rest_framework_json_api/mixins.py +++ /dev/null @@ -1,38 +0,0 @@ -""" -Class Mixins. -""" -import warnings - - -class MultipleIDMixin(object): - """ - Override get_queryset for multiple id support - - .. warning:: - - MultipleIDMixin is deprecated because it does not comply with http://jsonapi.org/format. - Instead add :py:class:`django_filters.DjangoFilterBackend` to your - list of `filter_backends` and change client usage from: - ``?ids[]=id1,id2,...,idN`` to ``'?filter[id.in]=id1,id2,...,idN`` - - """ - def __init__(self, *args, **kwargs): - warnings.warn("MultipleIDMixin is deprecated. " - "Instead add django_filters.DjangoFilterBackend to your " - "list of 'filter_backends' and change client usage from: " - "'?ids[]=id1,id2,...,idN' to '?filter[id.in]=id1,id2,...,idN'", - DeprecationWarning) - super(MultipleIDMixin, self).__init__(*args, **kwargs) - - def get_queryset(self): - """ - Override :meth:``get_queryset`` - """ - queryset = super(MultipleIDMixin, self).get_queryset() - if hasattr(self.request, 'query_params'): - ids = dict(self.request.query_params).get('ids[]') - else: - ids = dict(self.request.QUERY_PARAMS).get('ids[]') - if ids: - queryset = queryset.filter(id__in=ids) - return queryset diff --git a/rest_framework_json_api/pagination.py b/rest_framework_json_api/pagination.py index db09bb7d..2e57b937 100644 --- a/rest_framework_json_api/pagination.py +++ b/rest_framework_json_api/pagination.py @@ -1,7 +1,6 @@ """ Pagination fields """ -import warnings from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination, PageNumberPagination @@ -102,65 +101,3 @@ def get_paginated_response(self, data): ('prev', self.get_previous_link()) ]) }) - - -class PageNumberPagination(JsonApiPageNumberPagination): - """ - .. warning:: - - PageNumberPagination is deprecated. Use JsonApiPageNumberPagination instead. - If you want to retain current defaults you will need to implement custom - pagination class explicitly setting `page_query_param = "page"` and - `page_size_query_param = "page_size"`. - See changelog for more details. - - A paginator that uses non-JSON:API query parameters (default: - 'page' and 'page_size' instead of 'page[number]' and 'page[size]'). - """ - page_query_param = 'page' - page_size_query_param = 'page_size' - - def __init__(self): - if type(self) == PageNumberPagination: - warn = self.page_query_param == 'page' or self.page_size_query_param == 'page_size' - else: # inherited class doesn't override the attributes? - warn = ('page_query_param' not in type(self).__dict__ or - 'page_size_query_param' not in type(self).__dict__) - if warn: - warnings.warn( - 'PageNumberPagination is deprecated. Use JsonApiPageNumberPagination instead. ' - 'If you want to retain current defaults you will need to implement custom ' - 'pagination class explicitly setting `page_query_param = "page"` and ' - '`page_size_query_param = "page_size"`. ' - 'See changelog for more details.', - DeprecationWarning) - - super(PageNumberPagination, self).__init__() - - -class LimitOffsetPagination(JsonApiLimitOffsetPagination): - """ - .. warning:: - - LimitOffsetPagination is deprecated. Use JsonApiLimitOffsetPagination instead. - If you want to retain current defaults you will need to implement custom - pagination class explicitly setting `max_limit = None`. - See changelog for more details. - - A paginator that uses a different max_limit from `JsonApiLimitOffsetPagination`. - """ - max_limit = None - - def __init__(self): - if type(self) == LimitOffsetPagination: - warn = self.max_limit is None - else: - warn = 'max_limit' not in type(self).__dict__ - if warn: - warnings.warn( - 'LimitOffsetPagination is deprecated. Use JsonApiLimitOffsetPagination instead. ' - 'If you want to retain current defaults you will need to implement custom ' - 'pagination class explicitly setting `max_limit = None`. ' - 'See changelog for more details.', - DeprecationWarning) - super(LimitOffsetPagination, self).__init__() diff --git a/rest_framework_json_api/parsers.py b/rest_framework_json_api/parsers.py index 2184c342..2742302c 100644 --- a/rest_framework_json_api/parsers.py +++ b/rest_framework_json_api/parsers.py @@ -37,26 +37,26 @@ class JSONParser(parsers.JSONParser): @staticmethod def parse_attributes(data): attributes = data.get('attributes') - uses_format_translation = json_api_settings.format_type + uses_format_translation = json_api_settings.FORMAT_FIELD_NAMES if not attributes: return dict() elif uses_format_translation: # convert back to python/rest_framework's preferred underscore format - return utils._format_object(attributes, 'underscore') + return utils.format_field_names(attributes, 'underscore') else: return attributes @staticmethod def parse_relationships(data): - uses_format_translation = json_api_settings.format_type + uses_format_translation = json_api_settings.FORMAT_FIELD_NAMES relationships = data.get('relationships') if not relationships: relationships = dict() elif uses_format_translation: # convert back to python/rest_framework's preferred underscore format - relationships = utils._format_object(relationships, 'underscore') + relationships = utils.format_field_names(relationships, 'underscore') # Parse the relationships parsed_relationships = dict() diff --git a/rest_framework_json_api/renderers.py b/rest_framework_json_api/renderers.py index ba41a061..55236113 100644 --- a/rest_framework_json_api/renderers.py +++ b/rest_framework_json_api/renderers.py @@ -81,7 +81,7 @@ def extract_attributes(cls, fields, resource): field_name: resource.get(field_name) }) - return utils._format_object(data) + return utils.format_field_names(data) @classmethod def extract_relationships(cls, fields, resource, resource_instance): @@ -296,7 +296,7 @@ def extract_relationships(cls, fields, resource, resource_instance): }) continue - return utils._format_object(data) + return utils.format_field_names(data) @classmethod def extract_relation_instance(cls, field, resource_instance): @@ -410,7 +410,7 @@ def extract_included(cls, fields, resource, resource_instance, included_resource getattr(serializer, '_poly_force_type_resolution', False) ) included_cache[new_item['type']][new_item['id']] = \ - utils._format_object(new_item) + utils.format_field_names(new_item) cls.extract_included( serializer_fields, serializer_resource, @@ -432,7 +432,7 @@ def extract_included(cls, fields, resource, resource_instance, included_resource relation_type, getattr(field, '_poly_force_type_resolution', False) ) - included_cache[new_item['type']][new_item['id']] = utils._format_object( + included_cache[new_item['type']][new_item['id']] = utils.format_field_names( new_item ) cls.extract_included( @@ -596,7 +596,7 @@ def render(self, data, accepted_media_type=None, renderer_context=None): ) meta = self.extract_meta(serializer, resource) if meta: - json_resource_obj.update({'meta': utils._format_object(meta)}) + json_resource_obj.update({'meta': utils.format_field_names(meta)}) json_api_data.append(json_resource_obj) self.extract_included( @@ -613,7 +613,7 @@ def render(self, data, accepted_media_type=None, renderer_context=None): meta = self.extract_meta(serializer, serializer_data) if meta: - json_api_data.update({'meta': utils._format_object(meta)}) + json_api_data.update({'meta': utils.format_field_names(meta)}) self.extract_included( fields, serializer_data, resource_instance, included_resources, included_cache @@ -654,7 +654,7 @@ def render(self, data, accepted_media_type=None, renderer_context=None): render_data['included'].append(included_cache[included_type][included_id]) if json_api_meta: - render_data['meta'] = utils._format_object(json_api_meta) + render_data['meta'] = utils.format_field_names(json_api_meta) return super(JSONRenderer, self).render( render_data, accepted_media_type, renderer_context diff --git a/rest_framework_json_api/settings.py b/rest_framework_json_api/settings.py index 6c7eeffe..1385630c 100644 --- a/rest_framework_json_api/settings.py +++ b/rest_framework_json_api/settings.py @@ -14,11 +14,6 @@ 'FORMAT_TYPES': False, 'PLURALIZE_TYPES': False, 'UNIFORM_EXCEPTIONS': False, - - # deprecated settings to be removed in the future - 'FORMAT_KEYS': None, - 'FORMAT_RELATION_KEYS': None, - 'PLURALIZE_RELATION_TYPE': None, } @@ -42,13 +37,6 @@ def __getattr__(self, attr): setattr(self, attr, value) return value - @property - def format_type(self): - if self.FORMAT_KEYS is not None: - return self.FORMAT_KEYS - - return self.FORMAT_FIELD_NAMES - json_api_settings = JSONAPISettings() diff --git a/rest_framework_json_api/utils.py b/rest_framework_json_api/utils.py index ff299772..ea5fd47c 100644 --- a/rest_framework_json_api/utils.py +++ b/rest_framework_json_api/utils.py @@ -1,7 +1,6 @@ import copy import inspect import operator -import warnings from collections import OrderedDict import inflection @@ -113,71 +112,9 @@ def format_field_names(obj, format_type=None): return obj -def _format_object(obj, format_type=None): - """Depending on settings calls either `format_keys` or `format_field_names`""" - - if json_api_settings.FORMAT_KEYS is not None: - return format_keys(obj, format_type) - - return format_field_names(obj, format_type) - - -def format_keys(obj, format_type=None): - """ - .. warning:: - - `format_keys` function and `JSON_API_FORMAT_KEYS` setting are deprecated and will be - removed in the future. - Use `format_field_names` and `JSON_API_FORMAT_FIELD_NAMES` instead. Be aware that - `format_field_names` only formats keys and preserves value. - - Takes either a dict or list and returns it with camelized keys only if - JSON_API_FORMAT_KEYS is set. - - :format_type: Either 'dasherize', 'camelize', 'capitalize' or 'underscore' - """ - warnings.warn( - "`format_keys` function and `JSON_API_FORMAT_KEYS` setting are deprecated and will be " - "removed in the future. " - "Use `format_field_names` and `JSON_API_FORMAT_FIELD_NAMES` instead. Be aware that " - "`format_field_names` only formats keys and preserves value.", - DeprecationWarning - ) - - if format_type is None: - format_type = json_api_settings.FORMAT_KEYS - - if format_type in ('dasherize', 'camelize', 'underscore', 'capitalize'): - - if isinstance(obj, dict): - formatted = OrderedDict() - for key, value in obj.items(): - if format_type == 'dasherize': - # inflection can't dasherize camelCase - key = inflection.underscore(key) - formatted[inflection.dasherize(key)] \ - = format_keys(value, format_type) - elif format_type == 'camelize': - formatted[inflection.camelize(key, False)] \ - = format_keys(value, format_type) - elif format_type == 'capitalize': - formatted[inflection.camelize(key)] \ - = format_keys(value, format_type) - elif format_type == 'underscore': - formatted[inflection.underscore(key)] \ - = format_keys(value, format_type) - return formatted - if isinstance(obj, list): - return [format_keys(item, format_type) for item in obj] - else: - return obj - else: - return obj - - def format_value(value, format_type=None): if format_type is None: - format_type = json_api_settings.format_type + format_type = json_api_settings.FORMAT_FIELD_NAMES if format_type == 'dasherize': # inflection can't dasherize camelCase value = inflection.underscore(value) @@ -191,26 +128,6 @@ def format_value(value, format_type=None): return value -def format_relation_name(value, format_type=None): - """ - .. warning:: - - The 'format_relation_name' function has been renamed 'format_resource_type' and the - settings are now 'JSON_API_FORMAT_TYPES' and 'JSON_API_PLURALIZE_TYPES' instead of - 'JSON_API_FORMAT_RELATION_KEYS' and 'JSON_API_PLURALIZE_RELATION_TYPE' - """ - warnings.warn( - "The 'format_relation_name' function has been renamed 'format_resource_type' and the " - "settings are now 'JSON_API_FORMAT_TYPES' and 'JSON_API_PLURALIZE_TYPES' instead of " - "'JSON_API_FORMAT_RELATION_KEYS' and 'JSON_API_PLURALIZE_RELATION_TYPE'", - DeprecationWarning - ) - if format_type is None: - format_type = json_api_settings.FORMAT_RELATION_KEYS - pluralize = json_api_settings.PLURALIZE_RELATION_TYPE - return format_resource_type(value, format_type, pluralize) - - def format_resource_type(value, format_type=None, pluralize=None): if format_type is None: format_type = json_api_settings.FORMAT_TYPES diff --git a/rest_framework_json_api/views.py b/rest_framework_json_api/views.py index 0970cb1d..4329aaeb 100644 --- a/rest_framework_json_api/views.py +++ b/rest_framework_json_api/views.py @@ -1,4 +1,3 @@ -import warnings from collections.abc import Iterable from django.core.exceptions import ImproperlyConfigured @@ -31,45 +30,6 @@ ) -class PrefetchForIncludesHelperMixin(object): - - def __init__(self, *args, **kwargs): - warnings.warn("PrefetchForIncludesHelperMixin is deprecated. " - "Use PreloadIncludesMixin instead", - DeprecationWarning) - super(PrefetchForIncludesHelperMixin, self).__init__(*args, **kwargs) - - def get_queryset(self): - """ - This viewset provides a helper attribute to prefetch related models - based on the include specified in the URL. - - __all__ can be used to specify a prefetch which should be done regardless of the include - - .. code:: python - - # When MyViewSet is called with ?include=author it will prefetch author and authorbio - class MyViewSet(viewsets.ModelViewSet): - queryset = Book.objects.all() - prefetch_for_includes = { - '__all__': [], - 'author': ['author', 'author__authorbio'], - 'category.section': ['category'] - } - """ - qs = super(PrefetchForIncludesHelperMixin, self).get_queryset() - if not hasattr(self, 'prefetch_for_includes'): - return qs - - includes = self.request.GET.get('include', '').split(',') - for inc in includes + ['__all__']: - prefetches = self.prefetch_for_includes.get(inc) - if prefetches: - qs = qs.prefetch_related(*prefetches) - - return qs - - class PreloadIncludesMixin(object): """ This mixin provides a helper attributes to select or prefetch related models