strawberry-graphql / strawberry

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

Pydantic type `all_fields` does not include computed fields #3607

Open thearchitector opened 1 month ago

thearchitector commented 1 month ago

Describe the Bug

If a Pydantic model defines a computed field, those fields are excluded from the model when using the all_fields kwarg to the strawberry.experimental.pydantic.type.

I would expect them to be included by default as well, or for there to be a flag like include_computed_fields that I could specify to ensure they're exposed by the GraphQL type.

Extending the converted model to include the computed field with their proper type works. strawberry.auto does not work.

See the following:

import strawberry
from pydantic import BaseModel, computed_field

class SomeModel(BaseModel):
    name: str

    @computed_field
    @property
    def normalized_name(self) -> str:
        return f"normalized:{self.name}"

@strawberry.experimental.pydantic.type(SomeModel, all_fields=True)
class ModelType:
    pass
    # normalized_name: str

@strawberry.type
class Query:
    @strawberry.field(graphql_type=ModelType)
    def model(self) -> SomeModel:
        return SomeModel(name="hello")

res = strawberry.Schema(query=Query).execute_sync(
    """
        query {
            model {
                name
                normalizedName
            }
        }
    """
)
print(res)

In the above code, normalizedName doesn't exist on the schema and therefore returns an error. After uncommenting the field from the type, the query returns properly.

If the computed field in the converted type is typed with strawberry.auto, I get TypeError: ModelType fields cannot be resolved. Unexpected type 'typing.Any'

System Information

Other information

I'm not sure if this is a bug or not, but the return typing for the query is also a bit funky. I cannot type the field to return the converted model type. Instead, I have to type the field as the actual pydantic model and specify graphql_type in the field arguments. During runtime, both work (incorrect typing and valid typing).

Upvote & Fund

Fund with Polar