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

Resolves #840
This commit is contained in:
Vyacheslav Matyukhin 2019-12-31 16:55:45 +03:00 committed by Jonathan Kim
parent f661cf8335
commit efe210f8ac
3 changed files with 45 additions and 0 deletions

View File

@ -64,6 +64,9 @@ class Reporter(models.Model):
if self.reporter_type == 2: # quick and dirty way without enums if self.reporter_type == 2: # quick and dirty way without enums
self.__class__ = CNNReporter self.__class__ = CNNReporter
def some_method(self):
return 123
class CNNReporterManager(models.Manager): class CNNReporterManager(models.Manager):
def get_queryset(self): def get_queryset(self):

View File

@ -318,6 +318,30 @@ def test_django_objecttype_fields_exclude_type_checking():
exclude = "foo" 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: class TestDjangoObjectType:
@pytest.fixture @pytest.fixture
def PetModel(self): def PetModel(self):

View File

@ -33,6 +33,24 @@ def construct_fields(
): ):
_model_fields = get_model_fields(model) _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() fields = OrderedDict()
for name, field in _model_fields: for name, field in _model_fields:
is_not_in_only = only_fields and name not in only_fields is_not_in_only = only_fields and name not in only_fields