Skip to content
Closed
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: 2 additions & 0 deletions graphene_django/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
27 changes: 26 additions & 1 deletion graphene_django/tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
13 changes: 12 additions & 1 deletion graphene_django/types.py
Original file line number Diff line number Diff line change
@@ -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)

Expand All @@ -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


Expand Down