strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
4.01k stars 533 forks source link

Use pydantic model as a scalar with `strawberry.auto` #2252

Open benzolium opened 2 years ago

benzolium commented 2 years ago

Add way of using pydantic model scalars without manually defining fields - just by using strawberry.auto

Feature Request Type

Description

I have a pydantic model, lets say:

class SomeNameModel(pydantic.BaseModel):
    name: str
    number: int

And I have a scalar:

@strawberry.scalar(
    name='SomeName',
    serialize=marshal_some_name,
    parse_value=unmarshal_some_name,
)
class SomeName(SomeNameModel):
    """SomeName scalar."""

I have a model which has uses that scalar:

class User(pydantic.BaseModel):
    some_name: SomeNameModel

When I'm trying to create a type from it:

@strawberry.experimental.pydantic.type(
    model=User,
)
class UserType:
    some_name: strawberry.auto

I'm getting an error:

Cannot find a Strawberry Type for <class 'SomeNameModel'> did you forget to register it?

If I change User to:

class User(pydantic.BaseModel):
    some_name: SomeName

I have a pydantic error:

RuntimeError: error checking inheritance of <strawberry.custom_scalar.ScalarWrapper object at 0x10adc2ce0> (type: ScalarWrapper)

However, this works (manual annotation of type):

@strawberry.experimental.pydantic.type(
    model=User,
)
class UserType:
    some_name: SomeName

Upvote & Fund

Fund with Polar

filwaline commented 5 months ago

I am also encountering the same issue because strawberry.auto is not working, and setting the flag all_field=True in strawberry.experimental.pydantic.type has also failed.

Even when scalar_overrides are set, strawberry.auto still fails to resolve the type.

def create_schema() -> strawberry.Schema:
    return strawberry.Schema(
        query=Query,
        mutation=Mutation,
        scalar_overrides={SomeNameModel: SomeName},
    )