Created
June 22, 2019 00:29
-
-
Save robertpro/599cc00e63a49279f63b5046490d0bbe to your computer and use it in GitHub Desktop.
Minimal python script to autogenerate graphene-django resolvers (GraphQL)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import django | |
django.setup() | |
from django.apps import apps | |
from django.contrib.contenttypes.fields import GenericForeignKey | |
from django.contrib.postgres.fields import ArrayField | |
app = "app" | |
models = apps.get_app_config(app).get_models() | |
exempted_field_types = (ArrayField, GenericForeignKey) | |
exempted_field_names = ('id', '_field_status') | |
for model in models: | |
model_name = model.__name__ | |
fields_name = [ | |
field.name for field in model._meta.get_fields() | |
if field.name not in exempted_field_names and not isinstance(field, exempted_field_types) | |
] | |
fields = [f"'{field}': ['exact', 'in', 'icontains', 'istartswith']" for field in fields_name] | |
fields_code = '' | |
for i in range(len(fields)): | |
field = fields[i] | |
if i == 0: | |
fields_code += f' {field},' | |
else: | |
fields_code += f'\n {field},' | |
print(f""" | |
class {model_name}Node(DjangoObjectType): | |
class Meta: | |
model = {model_name} | |
filter_fields = {{ | |
{fields_code} | |
}} | |
interfaces = (graphene.relay.Node,) | |
@classmethod | |
@login_required | |
def get_queryset(cls, queryset, info): | |
return queryset | |
""") | |
models = list(apps.get_app_config(app).get_models()) | |
print("\n\nclass Query(graphene.ObjectType):") | |
def convert(name): | |
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) | |
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | |
for model in models: | |
model_name = model.__name__ | |
print(f" {convert(model_name)} = graphene.relay.Node.Field({model_name}Node)") | |
print(f" all_{convert(model_name)}s = DjangoFilterConnectionField({model_name}Node)") | |
print() | |
for model in models: | |
model_name = model.__name__ | |
attrib = convert(model_name.replace("Node", "")) | |
print(" @login_required") | |
print(f" def resolve_all_{attrib}s(self, info, **kwargs):") | |
print(" return None") | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment