Skip to content

Validate Meta.fields and Meta.exclude on DjangoObjectType #842

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 31, 2019
Merged
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
Validate Meta.fields and Meta.exclude on DjangoObjectType
Resolves #840
  • Loading branch information
berekuk committed Dec 29, 2019
commit 42b97e9d477b2d102e1207b01972987d586a6842
3 changes: 3 additions & 0 deletions graphene_django/tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ def __init__(self, *args, **kwargs):
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):
Expand Down
24 changes: 24 additions & 0 deletions graphene_django/tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,30 @@ class Meta:
fields = "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):
Expand Down
18 changes: 18 additions & 0 deletions graphene_django/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down