Skip to content

Commit

Permalink
Avoid create field for auto generate OneToOneField product of an inhe…
Browse files Browse the repository at this point in the history
…ritance

Added better descriptions to generate fields
  • Loading branch information
Ernesto Perez Amigo committed Oct 30, 2017
1 parent 92bf657 commit a880bfd
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 101 deletions.
2 changes: 1 addition & 1 deletion graphene_django_extras/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from .types import DjangoObjectType, DjangoInputObjectType, DjangoListObjectType
from .subscriptions import *

VERSION = (0, 1, 0, 'alpha', '10')
VERSION = (0, 1, 0, 'alpha', '11')

__version__ = get_version(VERSION)

Expand Down
8 changes: 4 additions & 4 deletions graphene_django_extras/base_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class Meta:
filter_fields = new_filter_fields
registry = new_registry
skip_registry = new_skip_registry
description = 'Generated type for {} model'.format(new_model._meta.verbose_name)
description = 'Auto generated Type for {} model'.format(new_model._meta.verbose_name)

return GenericType

Expand All @@ -76,7 +76,7 @@ class Meta:
registry = new_registry
skip_registry = new_skip_registry
input_for = new_input_for
description = 'Generated input type for {} model'.format(new_model._meta.verbose_name)
description = ' Auto generated InputType for {} model'.format(new_model._meta.verbose_name)

return GenericInputType

Expand Down Expand Up @@ -109,7 +109,7 @@ class GenericForeignKeyType(graphene.ObjectType):
model_name = graphene.String()

class Meta:
description = " Generated Type for a GenericForeignKey model field "
description = ' Auto generated Type for a model\'s GenericForeignKey field '
default_resolver = resolver


Expand All @@ -119,4 +119,4 @@ class GenericForeignKeyInputType(graphene.InputObjectType):
model_name = graphene.Argument(graphene.String, required=True)

class Meta:
description = " Generated InputType for a GenericForeignKey model field "
description = ' Auto generated InputType for a model\'s GenericForeignKey field '
70 changes: 31 additions & 39 deletions graphene_django_extras/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.db import models
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from graphene import (Field, ID, Boolean, Dynamic, Enum, Float, Int, List, NonNull, String, UUID)
from graphene.types.datetime import DateTime, Time
from graphene.types.json import JSONString
Expand All @@ -28,7 +27,7 @@


def assert_valid_name(name):
"""Helper to assert that provided names are valid."""
""" Helper to assert that provided names are valid. """
assert COMPILED_NAME_PATTERN.match(name), 'Names must match /{}/ but "{}" does not.'.format(NAME_PATTERN, name)


Expand Down Expand Up @@ -118,16 +117,7 @@ def construct_fields(model, registry, only_fields, exclude_fields, input_flag=No
converted = convert_django_field_with_choices(field, registry, input_flag, nested_fields)

fields[name] = converted
"""
result = OrderedDict()
if input_flag:
ordered_keys = sorted(fields, key=lambda f: getattr(fields[f], 'kwargs', {}).get('required', None),
reverse=True)
[result.update({x: fields[x]}) for x in ordered_keys]
else:
result.update(fields)
return result
"""

return fields


Expand All @@ -145,20 +135,22 @@ def convert_django_field(field, registry=None, input_flag=None, nested_fields=Fa
@convert_django_field.register(models.GenericIPAddressField)
@convert_django_field.register(models.FileField)
def convert_field_to_string(field, registry=None, input_flag=None, nested_fields=False):
return String(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return String(description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(models.AutoField)
def convert_field_to_id(field, registry=None, input_flag=None, nested_fields=False):
if input_flag:
return ID(description=field.help_text or _('Django object unique identification field'),
return ID(description=field.help_text or 'Django object unique identification field',
required=input_flag == 'update')
return ID(description=field.help_text or _('Django object unique identification field'), required=not field.null)
return ID(description=field.help_text or 'Django object unique identification field', required=not field.null)


@convert_django_field.register(models.UUIDField)
def convert_field_to_uuid(field, registry=None, input_flag=None, nested_fields=False):
return UUID(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return UUID(description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(models.PositiveIntegerField)
Expand All @@ -167,7 +159,8 @@ def convert_field_to_uuid(field, registry=None, input_flag=None, nested_fields=F
@convert_django_field.register(models.BigIntegerField)
@convert_django_field.register(models.IntegerField)
def convert_field_to_int(field, registry=None, input_flag=None, nested_fields=False):
return Int(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return Int(description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(models.BooleanField)
Expand All @@ -180,29 +173,34 @@ def convert_field_to_boolean(field, registry=None, input_flag=None, nested_field

@convert_django_field.register(models.NullBooleanField)
def convert_field_to_nullboolean(field, registry=None, input_flag=None, nested_fields=False):
return Boolean(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return Boolean(description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(models.DecimalField)
@convert_django_field.register(models.FloatField)
@convert_django_field.register(models.DurationField)
def convert_field_to_float(field, registry=None, input_flag=None, nested_fields=False):
return Float(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return Float(description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(models.DateField)
def convert_date_to_string(field, registry=None, input_flag=None, nested_fields=False):
return Date(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return Date(description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(models.DateTimeField)
def convert_date_to_string(field, registry=None, input_flag=None, nested_fields=False):
return DateTime(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return DateTime(description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(models.TimeField)
def convert_time_to_string(field, registry=None, input_flag=None, nested_fields=False):
return Time(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return Time(description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(models.OneToOneRel)
Expand All @@ -217,11 +215,6 @@ def dynamic_type():
if not _type:
return

# We do this for a bug in Django 1.8, where null attr
# is not available in the OneToOneRel instance
# null = getattr(field, 'null', True)
# return Field(_type, required=not null)

return Field(_type, required=is_required(field) and input_flag == 'create')

return Dynamic(dynamic_type)
Expand All @@ -241,7 +234,6 @@ def dynamic_type():

if _type._meta.filter_fields and input_flag:
return DjangoFilterListField(_type, required=is_required(field) and input_flag == 'create')
# return DjangoFilterPaginateListField(_type, paginations=LimitOffsetGraphqlPagination())
return DjangoListField(_type, required=is_required(field) and input_flag == 'create')

return Dynamic(dynamic_type)
Expand All @@ -251,11 +243,9 @@ def dynamic_type():
@convert_django_field.register(models.ManyToOneRel)
def convert_many_rel_to_djangomodel(field, registry=None, input_flag=None, nested_fields=False):
model = field.related_model
_field = field

def dynamic_type():
if input_flag and not nested_fields:
# return DjangoListField(ID, required=is_required(_field) and input_flag == 'create')
return DjangoListField(ID)

_type = registry.get_type_for_model(model, for_input=input_flag)
Expand All @@ -264,7 +254,6 @@ def dynamic_type():

if _type._meta.filter_fields and input_flag:
return DjangoFilterListField(_type)
# return DjangoFilterPaginateListField(_type, paginations=LimitOffsetGraphqlPagination())
return DjangoListField(_type)

return Dynamic(dynamic_type)
Expand All @@ -276,19 +265,19 @@ def convert_field_to_djangomodel(field, registry=None, input_flag=None, nested_f
model = get_related_model(field)

def dynamic_type():
# Avoid create field for auto generate OneToOneField product of an inheritance
if isinstance(field, models.OneToOneField) and issubclass(field.model, field.related_model):
# Tengo k ver como saber cuando un field de tipo OneToOneField es creado por el usuario
# o es una llave foranea automatica producto de una herencia
return
if input_flag and not nested_fields:
return ID(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return ID(description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')

_type = registry.get_type_for_model(model, for_input=input_flag)
if not _type:
return

# return Field(_type, description=field.help_text or field.verbose_name, required=field.null)
return Field(_type, description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return Field(_type, description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')

return Dynamic(dynamic_type)

Expand All @@ -298,21 +287,24 @@ def convert_postgres_array_to_list(field, registry=None, input_flag=None, nested
base_type = convert_django_field(field.base_field)
if not isinstance(base_type, (List, NonNull)):
base_type = type(base_type)
return List(base_type, description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return List(base_type, description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(HStoreField)
@convert_django_field.register(JSONField)
def convert_postgres_field_to_string(field, registry=None, input_flag=None, nested_fields=False):
return JSONString(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return JSONString(description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(RangeField)
def convert_postgres_range_to_string(field, registry=None, input_flag=None, nested_fields=False):
inner_type = convert_django_field(field.base_field)
if not isinstance(inner_type, (List, NonNull)):
inner_type = type(inner_type)
return List(inner_type, description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create')
return List(inner_type, description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == 'create')


@convert_django_field.register(GenericForeignKey)
Expand Down
19 changes: 9 additions & 10 deletions graphene_django_extras/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import operator
from functools import partial

from django.utils.translation import ugettext_lazy as _
from graphene import Field, List, ID, Argument
from graphene_django.filter.utils import get_filtering_args_from_filterset
from graphene_django.utils import maybe_queryset, is_valid_django_model, DJANGO_FILTER_INSTALLED
Expand All @@ -20,7 +19,7 @@ class DjangoObjectField(Field):
def __init__(self, _type, preprocess_kwargs=None, *args, **kwargs):

kwargs.setdefault('args', {})
kwargs['id'] = ID(required=True, description=_('Django object unique identification field'))
kwargs['id'] = ID(required=True, description='Django object unique identification field')

preprocess_kwargs = preprocess_kwargs or kwargs_formatter
kwargs = preprocess_kwargs(**kwargs)
Expand Down Expand Up @@ -67,11 +66,11 @@ def __init__(self, _type, fields=None, extra_filter_meta=None,

if 'id' not in kwargs['args'].keys():
self.filtering_args.update({'id': Argument(ID,
description=_('Django object unique identification field'))})
kwargs['args'].update({'id': Argument(ID, description=_('Django object unique identification field'))})
description='Django object unique identification field')})
kwargs['args'].update({'id': Argument(ID, description='Django object unique identification field')})

if not kwargs.get('description', None):
kwargs['description'] = _('List of {} objects').format(_type._meta.model.__name__)
kwargs['description'] = '{} list'.format(_type._meta.model.__name__)

preprocess_kwargs = preprocess_kwargs or kwargs_formatter
kwargs = preprocess_kwargs(**kwargs)
Expand Down Expand Up @@ -135,8 +134,8 @@ def __init__(self, _type, pagination=None, fields=None, extra_filter_meta=None,
kwargs['args'].update(self.filtering_args)

if 'id' not in kwargs['args'].keys():
self.filtering_args.update({'id': Argument(ID, description=_('Django object unique identification field'))})
kwargs['args'].update({'id': Argument(ID, description=_('Django object unique identification field'))})
self.filtering_args.update({'id': Argument(ID, description='Django object unique identification field')})
kwargs['args'].update({'id': Argument(ID, description='Django object unique identification field')})

if pagination:
pagination_kwargs = list_pagination_factory(pagination)
Expand All @@ -145,7 +144,7 @@ def __init__(self, _type, pagination=None, fields=None, extra_filter_meta=None,
kwargs.update(**pagination_kwargs)

if not kwargs.get('description', None):
kwargs['description'] = _('List of {} objects').format(_type._meta.model.__name__)
kwargs['description'] = '{} list'.format(_type._meta.model.__name__)

preprocess_kwargs = preprocess_kwargs or kwargs_formatter
kwargs = preprocess_kwargs(**kwargs)
Expand Down Expand Up @@ -198,12 +197,12 @@ def __init__(self, _type, fields=None, extra_filter_meta=None, filterset_class=N
kwargs['args'].update(self.filtering_args)

if 'id' not in kwargs['args'].keys():
id_description = _('Django object unique identification field')
id_description = 'Django object unique identification field'
self.filtering_args.update({'id': Argument(ID, description=id_description)})
kwargs['args'].update({'id': Argument(ID, description=id_description)})

if not kwargs.get('description', None):
kwargs['description'] = _('List of {} objects').format(_type._meta.model.__name__)
kwargs['description'] = '{} list'.format(_type._meta.model.__name__)

preprocess_kwargs = preprocess_kwargs or kwargs_formatter
kwargs = preprocess_kwargs(**kwargs)
Expand Down
11 changes: 5 additions & 6 deletions graphene_django_extras/mutation.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
from collections import OrderedDict

from django.utils.translation import ugettext_lazy as _
from graphene import Boolean, List, Field, ID, Argument, ObjectType
from graphene.types.base import BaseOptions
from graphene.utils.deprecated import warn_deprecation
Expand Down Expand Up @@ -31,8 +30,8 @@ class DjangoSerializerMutation(ObjectType):
Serializer Mutation Type Definition
"""

ok = Boolean(description=_('Boolean field that return mutation result request.'))
errors = List(ErrorType, description=_('May contain more than one error for same field.'))
ok = Boolean(description='Boolean field that return mutation result request.')
errors = List(ErrorType, description='Errors list for the field')

class Meta:
abstract = True
Expand Down Expand Up @@ -97,7 +96,7 @@ def __init_subclass_with_meta__(cls, serializer_class=None, only_fields=(), excl
})
else:
global_arguments[operation].update({
'id': Argument(ID, required=True, description=_('Django object unique identification field'))
'id': Argument(ID, required=True, description='Django object unique identification field')
})
global_arguments[operation].update(arguments)

Expand All @@ -114,8 +113,8 @@ def __init_subclass_with_meta__(cls, serializer_class=None, only_fields=(), excl
update_resolver = get_unbound_function(update_mutation) if update_mutation else None

assert (create_resolver or delete_resolver or update_resolver), \
_('All the SerializerMutations must define at least one of his mutations methods in it: '
'\'create_mutation\', \'delete_mutation\' or \'update_mutation\'')
'All the SerializerMutations must define at least one of his mutations methods in it: ' \
'\'create_mutation\', \'delete_mutation\' or \'update_mutation\''

kwargs_formatter = kwargs_formatter or native_kwargs_formatter

Expand Down
Loading

0 comments on commit a880bfd

Please sign in to comment.