diff --git a/graphene_django/tests/models.py b/graphene_django/tests/models.py index 14a8367..44a5d8a 100644 --- a/graphene_django/tests/models.py +++ b/graphene_django/tests/models.py @@ -64,6 +64,9 @@ class Reporter(models.Model): if self.reporter_type == 2: # quick and dirty way without enums self.__class__ = CNNReporter + def some_method(self): + return 123 + class CNNReporterManager(models.Manager): def get_queryset(self): diff --git a/graphene_django/tests/test_types.py b/graphene_django/tests/test_types.py index 5186623..cb31a9c 100644 --- a/graphene_django/tests/test_types.py +++ b/graphene_django/tests/test_types.py @@ -318,6 +318,30 @@ def test_django_objecttype_fields_exclude_type_checking(): exclude = "foo" +@with_local_registry +def test_django_objecttype_fields_exclude_exist_on_model(): + with pytest.raises(Exception, match=r"Field .* doesn't exist"): + + class Reporter(DjangoObjectType): + class Meta: + model = ReporterModel + fields = ["first_name", "foo", "email"] + + with pytest.raises(Exception, match=r"Field .* doesn't exist"): + + class Reporter2(DjangoObjectType): + class Meta: + model = ReporterModel + exclude = ["first_name", "foo", "email"] + + with pytest.raises(Exception, match=r".* exists on model .* but it's not a field"): + + class Reporter3(DjangoObjectType): + class Meta: + model = ReporterModel + fields = ["first_name", "some_method", "email"] + + class TestDjangoObjectType: @pytest.fixture def PetModel(self): diff --git a/graphene_django/types.py b/graphene_django/types.py index ec426f1..4824c45 100644 --- a/graphene_django/types.py +++ b/graphene_django/types.py @@ -33,6 +33,24 @@ def construct_fields( ): _model_fields = get_model_fields(model) + # Validate the given fields against the model's fields. + model_field_names = set(field[0] for field in _model_fields) + for fields_list in (only_fields, exclude_fields): + if not fields_list: + continue + for name in fields_list: + if name in model_field_names: + continue + + if hasattr(model, name): + raise Exception( + '"{}" exists on model {} but it\'s not a field.'.format(name, model) + ) + else: + raise Exception( + 'Field "{}" doesn\'t exist on model {}.'.format(name, model) + ) + fields = OrderedDict() for name, field in _model_fields: is_not_in_only = only_fields and name not in only_fields