diff --git a/graphene_django/settings.py b/graphene_django/settings.py index 46d70ee15..c3301cd33 100644 --- a/graphene_django/settings.py +++ b/graphene_django/settings.py @@ -35,6 +35,8 @@ 'RELAY_CONNECTION_ENFORCE_FIRST_OR_LAST': False, # Max items returned in ConnectionFields / FilterConnectionFields 'RELAY_CONNECTION_MAX_LIMIT': 100, + # Set to True if you want all models to include ForeignKey id fields + 'INCLUDE_FOREIGNKEY_IDS': False } if settings.DEBUG: diff --git a/graphene_django/tests/test_types.py b/graphene_django/tests/test_types.py index 83d9b4070..4b2bb076e 100644 --- a/graphene_django/tests/test_types.py +++ b/graphene_django/tests/test_types.py @@ -4,7 +4,8 @@ from graphene.relay import Node from .. import registry -from ..types import DjangoObjectType +from ..settings import graphene_settings +from ..types import DjangoObjectType, construct_fields from .models import Article as ArticleModel from .models import Reporter as ReporterModel @@ -176,3 +177,27 @@ class Meta: fields = list(Reporter._meta.fields.keys()) assert 'email' not in fields + + +def test_construct_fields_ignores_fkids_by_default(): + fields = construct_fields( + ArticleModel, + registry.registry, + (), () + ) + + assert 'reporter_id' not in fields + assert 'editor_id' not in fields + + +def test_construct_fields_adds_fkids_when_setting_is_true(): + graphene_settings.INCLUDE_FOREIGNKEY_IDS = True + fields = construct_fields( + ArticleModel, + registry.registry, + (), () + ) + graphene_settings.INCLUDE_FOREIGNKEY_IDS = False + + assert 'reporter_id' in fields + assert 'editor_id' in fields diff --git a/graphene_django/types.py b/graphene_django/types.py index 684863a89..be2a892be 100644 --- a/graphene_django/types.py +++ b/graphene_django/types.py @@ -1,13 +1,15 @@ from collections import OrderedDict +from django.db.models import ForeignKey from django.utils.functional import SimpleLazyObject from graphene import Field from graphene.relay import Connection, Node from graphene.types.objecttype import ObjectType, ObjectTypeOptions from graphene.types.utils import yank_fields_from_attrs -from .converter import convert_django_field_with_choices +from .converter import convert_django_field_with_choices, convert_field_to_id from .registry import Registry, get_global_registry +from .settings import graphene_settings from .utils import (DJANGO_FILTER_INSTALLED, get_model_fields, is_valid_django_model) @@ -30,6 +32,15 @@ def construct_fields(model, registry, only_fields, exclude_fields): converted = convert_django_field_with_choices(field, registry) fields[name] = converted + attname = getattr(field, 'attname', '') + add_foreignkey_attname = all([ + isinstance(field, ForeignKey), + graphene_settings.INCLUDE_FOREIGNKEY_IDS, + attname not in fields, + ]) + if add_foreignkey_attname: + fields[field.attname] = convert_field_to_id(field) + return fields