strawberry-graphql / strawberry-django

Strawberry GraphQL Django extension
https://strawberry.rocks/docs/django
MIT License
404 stars 117 forks source link

Dynamically constructing types for models #223

Closed rossm6 closed 1 year ago

rossm6 commented 1 year ago

For a given django model I want to dynamically construct a strawberry type. I've having problems though when it comes to unsupported django model fields.


class SomeModel(models.Model):
  id = HashidAutoField() // third party so unsupported
  name = models.CharField()

def resolver () -> str:
  return "DOH"

field = strawberry.django.field(resolver=resolver)

model_type = dataclasses.make_dataclass(
  SomeModel.__name__,
  [
    (
      'id',
      str,
     field
    ),
    ('name', strawberry.auto)
  ]
)

model_type(id="DOH") // Error: got an unexpected keyword argument 'id'

I've looked into it and I think it's because kwargs "init" is being set to False when dataclasses.fields is being called. And this is set to False if there is a basic resolver passed to the constructor. I can't see however where basic_resolver is defined prior to this call...??

Is there any way of resolving my approach, or, is there another approach entirely for providing a way of supporting the model fields not supported by this library?

Upvote & Fund

Fund with Polar

nrbnlulu commented 1 year ago

You can add your own resolvers for the field mapping

# before any strawberry_django.type call
from strawberry_django.fields.types import field_type_map

field_type_map[YourCustomField] = YourStrawberryType

Also, creating graphql types automatically is not best practice..

rossm6 commented 1 year ago

Thanks, I've got it working now.

Out of interest what do you have in mind when you say it's not best practice to automatically generate types?

nrbnlulu commented 1 year ago

security leaks ig..

bellini666 commented 1 year ago

This seems to be resolved so I'm closing the issue.

Please tell me if it is not or if we need to do something at our end still :)