Skip to content

Commit 36b0c58

Browse files
committed
Fix for apps that don't load contenttypes module.
PR django-json-api#319 brought support for generic relations. Unfortunately apps that don't add contenttypes to it's INSTALLED_APPS would crash and burn: ``` RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. ``` Also using `type(something) is object()` comparison as a safer alternative to `type(something) is type(None)`. If `something` happened to be `None` we would enter a branch that was never supposed to run.
1 parent da97874 commit 36b0c58

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ v2.3.0
33
* When `JSON_API_FORMAT_KEYS` is False (the default) do not translate request
44
attributes and relations to snake\_case format. This conversion was unexpected
55
and there was no way to turn it off.
6+
* Fix for apps that don't use `django.contrib.contenttypes`.
67

78
v2.2.0
89

rest_framework_json_api/utils.py

+11-4
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,28 @@
2020
try:
2121
from rest_framework.serializers import ManyRelatedField
2222
except ImportError:
23-
ManyRelatedField = type(None)
23+
ManyRelatedField = object()
2424

2525
try:
2626
from rest_framework_nested.relations import HyperlinkedRouterField
2727
except ImportError:
28-
HyperlinkedRouterField = type(None)
28+
HyperlinkedRouterField = object()
2929

3030
if django.VERSION >= (1, 9):
3131
from django.db.models.fields.related_descriptors import ManyToManyDescriptor, ReverseManyToOneDescriptor
32-
ReverseManyRelatedObjectsDescriptor = type(None)
33-
from django.contrib.contenttypes.fields import ReverseGenericManyToOneDescriptor
32+
ReverseManyRelatedObjectsDescriptor = object()
3433
else:
3534
from django.db.models.fields.related import ManyRelatedObjectsDescriptor as ManyToManyDescriptor
3635
from django.db.models.fields.related import ForeignRelatedObjectsDescriptor as ReverseManyToOneDescriptor
3736
from django.db.models.fields.related import ReverseManyRelatedObjectsDescriptor
37+
38+
# Generic relation descriptor from django.contrib.contenttypes.
39+
if 'django.contrib.contenttypes' not in settings.INSTALLED_APPS:
40+
# Target application does not use contenttypes. Importing would cause errors.
41+
ReverseGenericManyToOneDescriptor = object()
42+
elif django.VERSION >= (1, 9):
43+
from django.contrib.contenttypes.fields import ReverseGenericManyToOneDescriptor
44+
else:
3845
from django.contrib.contenttypes.fields import ReverseGenericRelatedObjectsDescriptor as ReverseGenericManyToOneDescriptor
3946

4047

0 commit comments

Comments
 (0)