Use compat implementations for the old meta api methods

This commit is contained in:
Pierre Dulac 2015-10-16 15:37:26 +02:00
parent 2cc3b417fa
commit 0a89478972
2 changed files with 30 additions and 17 deletions

View File

@ -71,6 +71,30 @@ except ImportError:
JSONField = None
# Models Options old meta api
# Django 1.8 introduced the `Options.get_fields` method that can be used to
# implement *old* meta api methods
# See: https://docs.djangoproject.com/en/1.9/ref/models/meta/#migrating-from-the-old-api
if django.VERSION >= (1, 8):
def get_all_related_objects(opts):
return [
f for f in opts.get_fields()
if (f.one_to_many or f.one_to_one) and f.auto_created
]
def get_all_related_many_to_many_objects(opts):
return [
f for f in opts.get_fields(include_hidden=True)
if f.many_to_many and f.auto_created
]
else:
def get_all_related_objects(opts):
return opts.get_all_related_objects()
def get_all_related_many_to_many_objects(opts):
return opts.get_all_related_many_to_many_objects()
# django-filter is optional
try:
import django_filters

View File

@ -13,6 +13,10 @@ from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils import six
from rest_framework.compat import (
get_all_related_objects, get_all_related_many_to_many_objects
)
FieldInfo = namedtuple('FieldResult', [
'pk', # Model field instance
'fields', # Dict of field name -> model field instance
@ -126,15 +130,7 @@ def _get_reverse_relationships(opts):
# See: https://code.djangoproject.com/ticket/24208
reverse_relations = OrderedDict()
# The backward implementation can be found in the Django Documentation
# See: https://docs.djangoproject.com/en/1.9/ref/models/meta/#migrating-from-the-old-api
related_objects = [
f for f in opts.get_fields()
if (f.one_to_many or f.one_to_one) and f.auto_created
]
for relation in related_objects:
for relation in get_all_related_objects(opts):
accessor_name = relation.get_accessor_name()
related = getattr(relation, 'related_model', relation.model)
reverse_relations[accessor_name] = RelationInfo(
@ -144,15 +140,8 @@ def _get_reverse_relationships(opts):
has_through_model=False
)
# The backward implementation can be found in the Django Documentation
# See: https://docs.djangoproject.com/en/1.9/ref/models/meta/#migrating-from-the-old-api
all_related_to_many_objects = [
f for f in opts.get_fields(include_hidden=True)
if f.many_to_many and f.auto_created
]
# Deal with reverse many-to-many relationships.
for relation in all_related_to_many_objects:
for relation in get_all_related_many_to_many_objects(opts):
accessor_name = relation.get_accessor_name()
related = getattr(relation, 'related_model', relation.model)
reverse_relations[accessor_name] = RelationInfo(