-
Hello! Is there a way to manually resolve objects to strawberry.type objects? @federation.type(keys=["id"])
class Provider:
id: strawberry.ID
name: str
slug: str
consumed_by: "Provider | None"
@classmethod
def resolve_reference(cls, info: Info, **kwargs):
obj: models.Provider = models.Provider.objects.get(id=kwargs["id"])
return Provider(
id=obj.pk,
name=obj.name,
slug=obj.slug,
consumed_by=obj.consumed_by,
) Which is fine for objects with few fields, but becomes messy for larger ones. Is there a helper function to be able to do something like this: def resolve_reference(cls, info: Info, **kwargs):
obj: models.Provider = models.Provider.objects.get(id=kwargs["id"])
return resolve_type(cls, obj, info) I've seen some code inside the library using @classmethod
def resolve_reference(cls, info: Info, **kwargs):
obj: models.Provider = models.Provider.objects.get(id=kwargs["id"])
strawberry_schema = info.schema.extensions["strawberry-definition"]
config = strawberry_schema.config
scalar_registry = strawberry_schema.schema_converter.scalar_registry
return convert_argument(obj, cls, scalar_registry=scalar_registry, config=config) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
@Object905 there isn't a way of automatically converting ORM models to Strawberry types (unless you use strawberry-django). The pattern I usually follow is to define a @federation.type(keys=["id"])
class Provider:
id: strawberry.ID
name: str
slug: str
consumed_by: "Provider | None"
@classmethod
def from_instance(cls, instance: models.Provider):
return cls(
id=obj.pk,
name=obj.name,
slug=obj.slug,
consumed_by=obj.consumed_by,
)
@classmethod
def resolve_reference(cls, info: Info, **kwargs):
obj: models.Provider = models.Provider.objects.get(id=kwargs["id"])
return Provider.from_instance(obj) |
Beta Was this translation helpful? Give feedback.
-
Well that would be a useful feature to have and would eliminate redundant code. Maybe in future I'll try to write some wrapper that would inherit target strawberry type, but actually will store all needed information and root object inside and resolve fields from it. For objects with simple fields and simple function resolvers (that may resolve both from themselves and root object), like in example it seems like it would be fairly simple (just get all fields with StrawberryConfig.default_resolver and construct object from struct). |
Beta Was this translation helpful? Give feedback.
@Object905 there isn't a way of automatically converting ORM models to Strawberry types (unless you use strawberry-django). The pattern I usually follow is to define a
from_instance
class method on the type where the conversion happens. Taking your example: