Skip to content

Commit efe210f

Browse files
berekukjkimbo
authored andcommitted
Validate Meta.fields and Meta.exclude on DjangoObjectType (#842)
Resolves #840
1 parent f661cf8 commit efe210f

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

graphene_django/tests/models.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,9 @@ def __init__(self, *args, **kwargs):
6464
if self.reporter_type == 2: # quick and dirty way without enums
6565
self.__class__ = CNNReporter
6666

67+
def some_method(self):
68+
return 123
69+
6770

6871
class CNNReporterManager(models.Manager):
6972
def get_queryset(self):

graphene_django/tests/test_types.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,30 @@ class Meta:
318318
exclude = "foo"
319319

320320

321+
@with_local_registry
322+
def test_django_objecttype_fields_exclude_exist_on_model():
323+
with pytest.raises(Exception, match=r"Field .* doesn't exist"):
324+
325+
class Reporter(DjangoObjectType):
326+
class Meta:
327+
model = ReporterModel
328+
fields = ["first_name", "foo", "email"]
329+
330+
with pytest.raises(Exception, match=r"Field .* doesn't exist"):
331+
332+
class Reporter2(DjangoObjectType):
333+
class Meta:
334+
model = ReporterModel
335+
exclude = ["first_name", "foo", "email"]
336+
337+
with pytest.raises(Exception, match=r".* exists on model .* but it's not a field"):
338+
339+
class Reporter3(DjangoObjectType):
340+
class Meta:
341+
model = ReporterModel
342+
fields = ["first_name", "some_method", "email"]
343+
344+
321345
class TestDjangoObjectType:
322346
@pytest.fixture
323347
def PetModel(self):

graphene_django/types.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,24 @@ def construct_fields(
3333
):
3434
_model_fields = get_model_fields(model)
3535

36+
# Validate the given fields against the model's fields.
37+
model_field_names = set(field[0] for field in _model_fields)
38+
for fields_list in (only_fields, exclude_fields):
39+
if not fields_list:
40+
continue
41+
for name in fields_list:
42+
if name in model_field_names:
43+
continue
44+
45+
if hasattr(model, name):
46+
raise Exception(
47+
'"{}" exists on model {} but it\'s not a field.'.format(name, model)
48+
)
49+
else:
50+
raise Exception(
51+
'Field "{}" doesn\'t exist on model {}.'.format(name, model)
52+
)
53+
3654
fields = OrderedDict()
3755
for name, field in _model_fields:
3856
is_not_in_only = only_fields and name not in only_fields

0 commit comments

Comments
 (0)