strawberry-django-plus
strawberry-django-plus copied to clipboard
Add support for a fields arg in the decorators
I think supporting fields/exclude like in DRF and Graphene is a nice feature to have. I did implement the fields arg locally like the following
dataclass_fields = list(_get_fields(django_type).values())
if fields == '__all__':
model_fields = list(model._meta.fields)
elif isinstance(fields, collections.abc.Sequence) and len(fields) > 0:
model_fields = [f for f in model._meta.fields if f.name in fields]
else:
model_fields = list()
cls.__annotations__ = {}
# update annotations and fields
for f in dataclass_fields:
annotation = f.type_annotation.annotation if f.type_annotation else f.type
if annotation is None:
annotation = StrawberryAnnotation(strawberry.auto)
cls.__annotations__[f.name] = annotation
setattr(cls, f.name, f)
for f in model_fields:
if cls.__annotations__.get(f.name):
continue
annotation = resolve_model_field_type(f, django_type)
if not annotation:
continue
cls.__annotations__[f.name] = annotation
setattr(cls, f.name, f.default or None)
now you can can do
@model_type(
models.Foo, filters=FooFilter, order=FooOrder, pagination=True,
fields='__all__'
)
class FooType(relay.Node):
pass
@model_type(
models.Foo,
fields=['x', 'y', 'z']
)
class FooType(relay.Node):
pass
I think it's a useful feature to have, what do you think? I did not test it outside queries, but I think it shouldn't be a problem.