We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Pydantic  - Usage of nested models with explicitly defined types/inputs- regression in Strawberry 0.92.0
Morning, 

Thanks for the awesome library! :+1: 

As of Strawberry 0.92 defining both, an input and a type for a nested pydantic model produces a confusion error on QUERY side:

>> Expected value of type 'AResponse' but got: <BInput instance>.

e.g. 

```python 
@strawberry.experimental.pydantic.input(model=A)                                                                                                                  
class AInput:                                                                                                                                                     
    a: strawberry.auto                                                                                                                                            
                                                                                                                                                                  
@strawberry.experimental.pydantic.input(model=B)                                                                                                                  
class BInput:                                                                                                                                                     
    b: strawberry.auto                                                                                                                                            
    a: strawberry.auto                                                                                                                                            
                                                                                                                                                                  
@strawberry.experimental.pydantic.type(model=A)                                                                                                                   
class AResponse:                                                                                                                                                     
     a: strawberry.auto                                                                                                                                            
                                                                                                                                                                  
@strawberry.experimental.pydantic.type(model=B)                                                                                                                   
class BResponse:                                                                                                                                                  
    b: strawberry.auto                                                                                                                                            
    a: strawberry.auto                                                                                                                                            
   
```

This may be a regression in behavior(the error got caught and exposed), rather than implementation.

Would be willing to contribute a PR if you could confirm that this is unexpected behaviour and not something that is intentional awaiting a rework down the line. Have a great weekend!


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `strawberry/experimental/pydantic/conversion.py`
Content:
```
1 from typing import Union, cast
2 
3 from strawberry.enum import EnumDefinition
4 from strawberry.field import StrawberryField
5 from strawberry.type import StrawberryList, StrawberryOptional, StrawberryType
6 from strawberry.union import StrawberryUnion
7 
8 
9 def _convert_from_pydantic_to_strawberry_type(
10     type_: Union[StrawberryType, type], data_from_model=None, extra=None
11 ):
12     data = data_from_model if data_from_model is not None else extra
13 
14     if isinstance(type_, StrawberryOptional):
15         if data is None:
16             return data
17         return _convert_from_pydantic_to_strawberry_type(
18             type_.of_type, data_from_model=data, extra=extra
19         )
20     if isinstance(type_, StrawberryUnion):
21         for option_type in type_.types:
22             if hasattr(option_type, "_pydantic_type"):
23                 source_type = option_type._pydantic_type  # type: ignore
24             else:
25                 source_type = cast(type, option_type)
26             if isinstance(data, source_type):
27                 return _convert_from_pydantic_to_strawberry_type(
28                     option_type, data_from_model=data, extra=extra
29                 )
30     if isinstance(type_, EnumDefinition):
31         return data
32     if isinstance(type_, StrawberryList):
33         items = []
34         for index, item in enumerate(data):
35             items.append(
36                 _convert_from_pydantic_to_strawberry_type(
37                     type_.of_type,
38                     data_from_model=item,
39                     extra=extra[index] if extra else None,
40                 )
41             )
42 
43         return items
44 
45     if hasattr(type_, "_type_definition"):
46         # in the case of an interface, the concrete type may be more specific
47         # than the type in the field definition
48         if hasattr(type(data), "_strawberry_type"):
49             type_ = type(data)._strawberry_type
50         return convert_pydantic_model_to_strawberry_class(
51             type_, model_instance=data_from_model, extra=extra
52         )
53 
54     return data
55 
56 
57 def convert_pydantic_model_to_strawberry_class(cls, *, model_instance=None, extra=None):
58     extra = extra or {}
59     kwargs = {}
60 
61     for field in cls._type_definition.fields:
62         field = cast(StrawberryField, field)
63         python_name = field.python_name
64 
65         data_from_extra = extra.get(python_name, None)
66         data_from_model = (
67             getattr(model_instance, python_name, None) if model_instance else None
68         )
69 
70         # only convert and add fields to kwargs if they are present in the `__init__`
71         # method of the class
72         if field.init:
73             kwargs[python_name] = _convert_from_pydantic_to_strawberry_type(
74                 field.type, data_from_model, extra=data_from_extra
75             )
76 
77     return cls(**kwargs)
78
```

Path: `strawberry/experimental/pydantic/object_type.py`
Content:
```
1 from __future__ import annotations
2 
3 import builtins
4 import dataclasses
5 import warnings
6 from functools import partial
7 from typing import (
8     TYPE_CHECKING,
9     Any,
10     Callable,
11     Dict,
12     List,
13     Optional,
14     Sequence,
15     Type,
16     cast,
17 )
18 
19 from pydantic import BaseModel
20 from pydantic.fields import ModelField
21 from typing_extensions import Literal
22 
23 from graphql import GraphQLResolveInfo
24 
25 import strawberry
26 from strawberry.arguments import UNSET
27 from strawberry.experimental.pydantic.conversion import (
28     convert_pydantic_model_to_strawberry_class,
29 )
30 from strawberry.experimental.pydantic.fields import get_basic_type
31 from strawberry.experimental.pydantic.utils import (
32     DataclassCreationFields,
33     ensure_all_auto_fields_in_pydantic,
34     get_default_factory_for_field,
35     get_private_fields,
36     sort_creation_fields,
37 )
38 from strawberry.field import StrawberryField
39 from strawberry.object_type import _process_type, _wrap_dataclass
40 from strawberry.schema_directive import StrawberrySchemaDirective
41 from strawberry.types.type_resolver import _get_fields
42 from strawberry.types.types import TypeDefinition
43 
44 from .exceptions import MissingFieldsListError, UnregisteredTypeException
45 
46 
47 def replace_pydantic_types(type_: Any):
48     origin = getattr(type_, "__origin__", None)
49     if origin is Literal:
50         # Literal does not have types in its __args__ so we return early
51         return type_
52     if hasattr(type_, "__args__"):
53         replaced_type = type_.copy_with(
54             tuple(replace_pydantic_types(t) for t in type_.__args__)
55         )
56 
57         if isinstance(replaced_type, TypeDefinition):
58             # TODO: Not sure if this is necessary. No coverage in tests
59             # TODO: Unnecessary with StrawberryObject
60 
61             replaced_type = builtins.type(
62                 replaced_type.name,
63                 (),
64                 {"_type_definition": replaced_type},
65             )
66 
67         return replaced_type
68 
69     if issubclass(type_, BaseModel):
70         if hasattr(type_, "_strawberry_type"):
71             return type_._strawberry_type
72         else:
73             raise UnregisteredTypeException(type_)
74 
75     return type_
76 
77 
78 def get_type_for_field(field: ModelField):
79     type_ = field.outer_type_
80     type_ = get_basic_type(type_)
81     type_ = replace_pydantic_types(type_)
82 
83     if not field.required:
84         type_ = Optional[type_]
85 
86     return type_
87 
88 
89 if TYPE_CHECKING:
90     from strawberry.experimental.pydantic.conversion_types import (
91         PydanticModel,
92         StrawberryTypeFromPydantic,
93     )
94 
95 
96 def type(
97     model: Type[PydanticModel],
98     *,
99     fields: Optional[List[str]] = None,
100     name: Optional[str] = None,
101     is_input: bool = False,
102     is_interface: bool = False,
103     description: Optional[str] = None,
104     directives: Optional[Sequence[StrawberrySchemaDirective]] = (),
105     all_fields: bool = False,
106 ) -> Callable[..., Type[StrawberryTypeFromPydantic[PydanticModel]]]:
107     def wrap(cls: Any) -> Type[StrawberryTypeFromPydantic[PydanticModel]]:
108         model_fields = model.__fields__
109         fields_set = set(fields) if fields else set([])
110 
111         if fields:
112             warnings.warn(
113                 "`fields` is deprecated, use `auto` type annotations instead",
114                 DeprecationWarning,
115             )
116 
117         existing_fields = getattr(cls, "__annotations__", {})
118         fields_set = fields_set.union(
119             set(name for name, typ in existing_fields.items() if typ is strawberry.auto)
120         )
121 
122         if all_fields:
123             if fields_set:
124                 warnings.warn(
125                     "Using all_fields overrides any explicitly defined fields "
126                     "in the model, using both is likely a bug",
127                     stacklevel=2,
128                 )
129             fields_set = set(model_fields.keys())
130 
131         if not fields_set:
132             raise MissingFieldsListError(cls)
133 
134         ensure_all_auto_fields_in_pydantic(
135             model=model, auto_fields=fields_set, cls_name=cls.__name__
136         )
137 
138         all_model_fields: List[DataclassCreationFields] = [
139             DataclassCreationFields(
140                 name=field_name,
141                 type_annotation=get_type_for_field(field),
142                 field=StrawberryField(
143                     python_name=field.name,
144                     graphql_name=field.alias if field.has_alias else None,
145                     # always unset because we use default_factory instead
146                     default=UNSET,
147                     default_factory=get_default_factory_for_field(field),
148                     type_annotation=get_type_for_field(field),
149                     description=field.field_info.description,
150                 ),
151             )
152             for field_name, field in model_fields.items()
153             if field_name in fields_set
154         ]
155 
156         wrapped = _wrap_dataclass(cls)
157         extra_fields = cast(List[dataclasses.Field], _get_fields(wrapped))
158         private_fields = get_private_fields(wrapped)
159 
160         all_model_fields.extend(
161             (
162                 DataclassCreationFields(
163                     name=field.name,
164                     type_annotation=field.type,
165                     field=field,
166                 )
167                 for field in extra_fields + private_fields
168                 if field.type != strawberry.auto
169             )
170         )
171 
172         # Sort fields so that fields with missing defaults go first
173         sorted_fields = sort_creation_fields(all_model_fields)
174 
175         # Implicitly define `is_type_of` to support interfaces/unions that use
176         # pydantic objects (not the corresponding strawberry type)
177         @classmethod  # type: ignore
178         def is_type_of(cls: Type, obj: Any, _info: GraphQLResolveInfo) -> bool:
179             return isinstance(obj, (cls, model))
180 
181         cls = dataclasses.make_dataclass(
182             cls.__name__,
183             [field.to_tuple() for field in sorted_fields],
184             bases=cls.__bases__,
185             namespace={"is_type_of": is_type_of},
186         )
187 
188         _process_type(
189             cls,
190             name=name,
191             is_input=is_input,
192             is_interface=is_interface,
193             description=description,
194             directives=directives,
195         )
196 
197         model._strawberry_type = cls  # type: ignore
198         cls._pydantic_type = model  # type: ignore
199 
200         def from_pydantic(
201             instance: PydanticModel, extra: Dict[str, Any] = None
202         ) -> StrawberryTypeFromPydantic[PydanticModel]:
203             return convert_pydantic_model_to_strawberry_class(
204                 cls=cls, model_instance=instance, extra=extra
205             )
206 
207         def to_pydantic(self) -> PydanticModel:
208             instance_kwargs = dataclasses.asdict(self)
209 
210             return model(**instance_kwargs)
211 
212         cls.from_pydantic = staticmethod(from_pydantic)
213         cls.to_pydantic = to_pydantic
214 
215         return cls
216 
217     return wrap
218 
219 
220 input = partial(type, is_input=True)
221 
222 interface = partial(type, is_interface=True)
223
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/strawberry/experimental/pydantic/conversion.py b/strawberry/experimental/pydantic/conversion.py
--- a/strawberry/experimental/pydantic/conversion.py
+++ b/strawberry/experimental/pydantic/conversion.py
@@ -45,6 +45,7 @@
     if hasattr(type_, "_type_definition"):
         # in the case of an interface, the concrete type may be more specific
         # than the type in the field definition
+        # don't check _strawberry_input_type because inputs can't be interfaces
         if hasattr(type(data), "_strawberry_type"):
             type_ = type(data)._strawberry_type
         return convert_pydantic_model_to_strawberry_class(
diff --git a/strawberry/experimental/pydantic/object_type.py b/strawberry/experimental/pydantic/object_type.py
--- a/strawberry/experimental/pydantic/object_type.py
+++ b/strawberry/experimental/pydantic/object_type.py
@@ -44,14 +44,14 @@
 from .exceptions import MissingFieldsListError, UnregisteredTypeException
 
 
-def replace_pydantic_types(type_: Any):
+def replace_pydantic_types(type_: Any, is_input: bool):
     origin = getattr(type_, "__origin__", None)
     if origin is Literal:
         # Literal does not have types in its __args__ so we return early
         return type_
     if hasattr(type_, "__args__"):
         replaced_type = type_.copy_with(
-            tuple(replace_pydantic_types(t) for t in type_.__args__)
+            tuple(replace_pydantic_types(t, is_input) for t in type_.__args__)
         )
 
         if isinstance(replaced_type, TypeDefinition):
@@ -67,18 +67,19 @@
         return replaced_type
 
     if issubclass(type_, BaseModel):
-        if hasattr(type_, "_strawberry_type"):
-            return type_._strawberry_type
+        attr = "_strawberry_input_type" if is_input else "_strawberry_type"
+        if hasattr(type_, attr):
+            return getattr(type_, attr)
         else:
             raise UnregisteredTypeException(type_)
 
     return type_
 
 
-def get_type_for_field(field: ModelField):
+def get_type_for_field(field: ModelField, is_input: bool):
     type_ = field.outer_type_
     type_ = get_basic_type(type_)
-    type_ = replace_pydantic_types(type_)
+    type_ = replace_pydantic_types(type_, is_input)
 
     if not field.required:
         type_ = Optional[type_]
@@ -138,14 +139,14 @@
         all_model_fields: List[DataclassCreationFields] = [
             DataclassCreationFields(
                 name=field_name,
-                type_annotation=get_type_for_field(field),
+                type_annotation=get_type_for_field(field, is_input),
                 field=StrawberryField(
                     python_name=field.name,
                     graphql_name=field.alias if field.has_alias else None,
                     # always unset because we use default_factory instead
                     default=UNSET,
                     default_factory=get_default_factory_for_field(field),
-                    type_annotation=get_type_for_field(field),
+                    type_annotation=get_type_for_field(field, is_input),
                     description=field.field_info.description,
                 ),
             )
@@ -194,7 +195,10 @@
             directives=directives,
         )
 
-        model._strawberry_type = cls  # type: ignore
+        if is_input:
+            model._strawberry_input_type = cls  # type: ignore
+        else:
+            model._strawberry_type = cls  # type: ignore
         cls._pydantic_type = model  # type: ignore
 
         def from_pydantic(

{"golden_diff": "diff --git a/strawberry/experimental/pydantic/conversion.py b/strawberry/experimental/pydantic/conversion.py\n--- a/strawberry/experimental/pydantic/conversion.py\n+++ b/strawberry/experimental/pydantic/conversion.py\n@@ -45,6 +45,7 @@\n     if hasattr(type_, \"_type_definition\"):\n         # in the case of an interface, the concrete type may be more specific\n         # than the type in the field definition\n+        # don't check _strawberry_input_type because inputs can't be interfaces\n         if hasattr(type(data), \"_strawberry_type\"):\n             type_ = type(data)._strawberry_type\n         return convert_pydantic_model_to_strawberry_class(\ndiff --git a/strawberry/experimental/pydantic/object_type.py b/strawberry/experimental/pydantic/object_type.py\n--- a/strawberry/experimental/pydantic/object_type.py\n+++ b/strawberry/experimental/pydantic/object_type.py\n@@ -44,14 +44,14 @@\n from .exceptions import MissingFieldsListError, UnregisteredTypeException\n \n \n-def replace_pydantic_types(type_: Any):\n+def replace_pydantic_types(type_: Any, is_input: bool):\n     origin = getattr(type_, \"__origin__\", None)\n     if origin is Literal:\n         # Literal does not have types in its __args__ so we return early\n         return type_\n     if hasattr(type_, \"__args__\"):\n         replaced_type = type_.copy_with(\n-            tuple(replace_pydantic_types(t) for t in type_.__args__)\n+            tuple(replace_pydantic_types(t, is_input) for t in type_.__args__)\n         )\n \n         if isinstance(replaced_type, TypeDefinition):\n@@ -67,18 +67,19 @@\n         return replaced_type\n \n     if issubclass(type_, BaseModel):\n-        if hasattr(type_, \"_strawberry_type\"):\n-            return type_._strawberry_type\n+        attr = \"_strawberry_input_type\" if is_input else \"_strawberry_type\"\n+        if hasattr(type_, attr):\n+            return getattr(type_, attr)\n         else:\n             raise UnregisteredTypeException(type_)\n \n     return type_\n \n \n-def get_type_for_field(field: ModelField):\n+def get_type_for_field(field: ModelField, is_input: bool):\n     type_ = field.outer_type_\n     type_ = get_basic_type(type_)\n-    type_ = replace_pydantic_types(type_)\n+    type_ = replace_pydantic_types(type_, is_input)\n \n     if not field.required:\n         type_ = Optional[type_]\n@@ -138,14 +139,14 @@\n         all_model_fields: List[DataclassCreationFields] = [\n             DataclassCreationFields(\n                 name=field_name,\n-                type_annotation=get_type_for_field(field),\n+                type_annotation=get_type_for_field(field, is_input),\n                 field=StrawberryField(\n                     python_name=field.name,\n                     graphql_name=field.alias if field.has_alias else None,\n                     # always unset because we use default_factory instead\n                     default=UNSET,\n                     default_factory=get_default_factory_for_field(field),\n-                    type_annotation=get_type_for_field(field),\n+                    type_annotation=get_type_for_field(field, is_input),\n                     description=field.field_info.description,\n                 ),\n             )\n@@ -194,7 +195,10 @@\n             directives=directives,\n         )\n \n-        model._strawberry_type = cls  # type: ignore\n+        if is_input:\n+            model._strawberry_input_type = cls  # type: ignore\n+        else:\n+            model._strawberry_type = cls  # type: ignore\n         cls._pydantic_type = model  # type: ignore\n \n         def from_pydantic(\n", "issue": "Pydantic  - Usage of nested models with explicitly defined types/inputs- regression in Strawberry 0.92.0\nMorning, \r\n\r\nThanks for the awesome library! :+1: \r\n\r\nAs of Strawberry 0.92 defining both, an input and a type for a nested pydantic model produces a confusion error on QUERY side:\r\n\r\n>> Expected value of type 'AResponse' but got: <BInput instance>.\r\n\r\ne.g. \r\n\r\n```python \r\n@strawberry.experimental.pydantic.input(model=A)                                                                                                                  \r\nclass AInput:                                                                                                                                                     \r\n    a: strawberry.auto                                                                                                                                            \r\n                                                                                                                                                                  \r\n@strawberry.experimental.pydantic.input(model=B)                                                                                                                  \r\nclass BInput:                                                                                                                                                     \r\n    b: strawberry.auto                                                                                                                                            \r\n    a: strawberry.auto                                                                                                                                            \r\n                                                                                                                                                                  \r\n@strawberry.experimental.pydantic.type(model=A)                                                                                                                   \r\nclass AResponse:                                                                                                                                                     \r\n     a: strawberry.auto                                                                                                                                            \r\n                                                                                                                                                                  \r\n@strawberry.experimental.pydantic.type(model=B)                                                                                                                   \r\nclass BResponse:                                                                                                                                                  \r\n    b: strawberry.auto                                                                                                                                            \r\n    a: strawberry.auto                                                                                                                                            \r\n   \r\n```\r\n\r\nThis may be a regression in behavior(the error got caught and exposed), rather than implementation.\r\n\r\nWould be willing to contribute a PR if you could confirm that this is unexpected behaviour and not something that is intentional awaiting a rework down the line. Have a great weekend!\r\n\n", "before_files": [{"content": "from typing import Union, cast\n\nfrom strawberry.enum import EnumDefinition\nfrom strawberry.field import StrawberryField\nfrom strawberry.type import StrawberryList, StrawberryOptional, StrawberryType\nfrom strawberry.union import StrawberryUnion\n\n\ndef _convert_from_pydantic_to_strawberry_type(\n    type_: Union[StrawberryType, type], data_from_model=None, extra=None\n):\n    data = data_from_model if data_from_model is not None else extra\n\n    if isinstance(type_, StrawberryOptional):\n        if data is None:\n            return data\n        return _convert_from_pydantic_to_strawberry_type(\n            type_.of_type, data_from_model=data, extra=extra\n        )\n    if isinstance(type_, StrawberryUnion):\n        for option_type in type_.types:\n            if hasattr(option_type, \"_pydantic_type\"):\n                source_type = option_type._pydantic_type  # type: ignore\n            else:\n                source_type = cast(type, option_type)\n            if isinstance(data, source_type):\n                return _convert_from_pydantic_to_strawberry_type(\n                    option_type, data_from_model=data, extra=extra\n                )\n    if isinstance(type_, EnumDefinition):\n        return data\n    if isinstance(type_, StrawberryList):\n        items = []\n        for index, item in enumerate(data):\n            items.append(\n                _convert_from_pydantic_to_strawberry_type(\n                    type_.of_type,\n                    data_from_model=item,\n                    extra=extra[index] if extra else None,\n                )\n            )\n\n        return items\n\n    if hasattr(type_, \"_type_definition\"):\n        # in the case of an interface, the concrete type may be more specific\n        # than the type in the field definition\n        if hasattr(type(data), \"_strawberry_type\"):\n            type_ = type(data)._strawberry_type\n        return convert_pydantic_model_to_strawberry_class(\n            type_, model_instance=data_from_model, extra=extra\n        )\n\n    return data\n\n\ndef convert_pydantic_model_to_strawberry_class(cls, *, model_instance=None, extra=None):\n    extra = extra or {}\n    kwargs = {}\n\n    for field in cls._type_definition.fields:\n        field = cast(StrawberryField, field)\n        python_name = field.python_name\n\n        data_from_extra = extra.get(python_name, None)\n        data_from_model = (\n            getattr(model_instance, python_name, None) if model_instance else None\n        )\n\n        # only convert and add fields to kwargs if they are present in the `__init__`\n        # method of the class\n        if field.init:\n            kwargs[python_name] = _convert_from_pydantic_to_strawberry_type(\n                field.type, data_from_model, extra=data_from_extra\n            )\n\n    return cls(**kwargs)\n", "path": "strawberry/experimental/pydantic/conversion.py"}, {"content": "from __future__ import annotations\n\nimport builtins\nimport dataclasses\nimport warnings\nfrom functools import partial\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    Type,\n    cast,\n)\n\nfrom pydantic import BaseModel\nfrom pydantic.fields import ModelField\nfrom typing_extensions import Literal\n\nfrom graphql import GraphQLResolveInfo\n\nimport strawberry\nfrom strawberry.arguments import UNSET\nfrom strawberry.experimental.pydantic.conversion import (\n    convert_pydantic_model_to_strawberry_class,\n)\nfrom strawberry.experimental.pydantic.fields import get_basic_type\nfrom strawberry.experimental.pydantic.utils import (\n    DataclassCreationFields,\n    ensure_all_auto_fields_in_pydantic,\n    get_default_factory_for_field,\n    get_private_fields,\n    sort_creation_fields,\n)\nfrom strawberry.field import StrawberryField\nfrom strawberry.object_type import _process_type, _wrap_dataclass\nfrom strawberry.schema_directive import StrawberrySchemaDirective\nfrom strawberry.types.type_resolver import _get_fields\nfrom strawberry.types.types import TypeDefinition\n\nfrom .exceptions import MissingFieldsListError, UnregisteredTypeException\n\n\ndef replace_pydantic_types(type_: Any):\n    origin = getattr(type_, \"__origin__\", None)\n    if origin is Literal:\n        # Literal does not have types in its __args__ so we return early\n        return type_\n    if hasattr(type_, \"__args__\"):\n        replaced_type = type_.copy_with(\n            tuple(replace_pydantic_types(t) for t in type_.__args__)\n        )\n\n        if isinstance(replaced_type, TypeDefinition):\n            # TODO: Not sure if this is necessary. No coverage in tests\n            # TODO: Unnecessary with StrawberryObject\n\n            replaced_type = builtins.type(\n                replaced_type.name,\n                (),\n                {\"_type_definition\": replaced_type},\n            )\n\n        return replaced_type\n\n    if issubclass(type_, BaseModel):\n        if hasattr(type_, \"_strawberry_type\"):\n            return type_._strawberry_type\n        else:\n            raise UnregisteredTypeException(type_)\n\n    return type_\n\n\ndef get_type_for_field(field: ModelField):\n    type_ = field.outer_type_\n    type_ = get_basic_type(type_)\n    type_ = replace_pydantic_types(type_)\n\n    if not field.required:\n        type_ = Optional[type_]\n\n    return type_\n\n\nif TYPE_CHECKING:\n    from strawberry.experimental.pydantic.conversion_types import (\n        PydanticModel,\n        StrawberryTypeFromPydantic,\n    )\n\n\ndef type(\n    model: Type[PydanticModel],\n    *,\n    fields: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    is_input: bool = False,\n    is_interface: bool = False,\n    description: Optional[str] = None,\n    directives: Optional[Sequence[StrawberrySchemaDirective]] = (),\n    all_fields: bool = False,\n) -> Callable[..., Type[StrawberryTypeFromPydantic[PydanticModel]]]:\n    def wrap(cls: Any) -> Type[StrawberryTypeFromPydantic[PydanticModel]]:\n        model_fields = model.__fields__\n        fields_set = set(fields) if fields else set([])\n\n        if fields:\n            warnings.warn(\n                \"`fields` is deprecated, use `auto` type annotations instead\",\n                DeprecationWarning,\n            )\n\n        existing_fields = getattr(cls, \"__annotations__\", {})\n        fields_set = fields_set.union(\n            set(name for name, typ in existing_fields.items() if typ is strawberry.auto)\n        )\n\n        if all_fields:\n            if fields_set:\n                warnings.warn(\n                    \"Using all_fields overrides any explicitly defined fields \"\n                    \"in the model, using both is likely a bug\",\n                    stacklevel=2,\n                )\n            fields_set = set(model_fields.keys())\n\n        if not fields_set:\n            raise MissingFieldsListError(cls)\n\n        ensure_all_auto_fields_in_pydantic(\n            model=model, auto_fields=fields_set, cls_name=cls.__name__\n        )\n\n        all_model_fields: List[DataclassCreationFields] = [\n            DataclassCreationFields(\n                name=field_name,\n                type_annotation=get_type_for_field(field),\n                field=StrawberryField(\n                    python_name=field.name,\n                    graphql_name=field.alias if field.has_alias else None,\n                    # always unset because we use default_factory instead\n                    default=UNSET,\n                    default_factory=get_default_factory_for_field(field),\n                    type_annotation=get_type_for_field(field),\n                    description=field.field_info.description,\n                ),\n            )\n            for field_name, field in model_fields.items()\n            if field_name in fields_set\n        ]\n\n        wrapped = _wrap_dataclass(cls)\n        extra_fields = cast(List[dataclasses.Field], _get_fields(wrapped))\n        private_fields = get_private_fields(wrapped)\n\n        all_model_fields.extend(\n            (\n                DataclassCreationFields(\n                    name=field.name,\n                    type_annotation=field.type,\n                    field=field,\n                )\n                for field in extra_fields + private_fields\n                if field.type != strawberry.auto\n            )\n        )\n\n        # Sort fields so that fields with missing defaults go first\n        sorted_fields = sort_creation_fields(all_model_fields)\n\n        # Implicitly define `is_type_of` to support interfaces/unions that use\n        # pydantic objects (not the corresponding strawberry type)\n        @classmethod  # type: ignore\n        def is_type_of(cls: Type, obj: Any, _info: GraphQLResolveInfo) -> bool:\n            return isinstance(obj, (cls, model))\n\n        cls = dataclasses.make_dataclass(\n            cls.__name__,\n            [field.to_tuple() for field in sorted_fields],\n            bases=cls.__bases__,\n            namespace={\"is_type_of\": is_type_of},\n        )\n\n        _process_type(\n            cls,\n            name=name,\n            is_input=is_input,\n            is_interface=is_interface,\n            description=description,\n            directives=directives,\n        )\n\n        model._strawberry_type = cls  # type: ignore\n        cls._pydantic_type = model  # type: ignore\n\n        def from_pydantic(\n            instance: PydanticModel, extra: Dict[str, Any] = None\n        ) -> StrawberryTypeFromPydantic[PydanticModel]:\n            return convert_pydantic_model_to_strawberry_class(\n                cls=cls, model_instance=instance, extra=extra\n            )\n\n        def to_pydantic(self) -> PydanticModel:\n            instance_kwargs = dataclasses.asdict(self)\n\n            return model(**instance_kwargs)\n\n        cls.from_pydantic = staticmethod(from_pydantic)\n        cls.to_pydantic = to_pydantic\n\n        return cls\n\n    return wrap\n\n\ninput = partial(type, is_input=True)\n\ninterface = partial(type, is_interface=True)\n", "path": "strawberry/experimental/pydantic/object_type.py"}], "after_files": [{"content": "from typing import Union, cast\n\nfrom strawberry.enum import EnumDefinition\nfrom strawberry.field import StrawberryField\nfrom strawberry.type import StrawberryList, StrawberryOptional, StrawberryType\nfrom strawberry.union import StrawberryUnion\n\n\ndef _convert_from_pydantic_to_strawberry_type(\n    type_: Union[StrawberryType, type], data_from_model=None, extra=None\n):\n    data = data_from_model if data_from_model is not None else extra\n\n    if isinstance(type_, StrawberryOptional):\n        if data is None:\n            return data\n        return _convert_from_pydantic_to_strawberry_type(\n            type_.of_type, data_from_model=data, extra=extra\n        )\n    if isinstance(type_, StrawberryUnion):\n        for option_type in type_.types:\n            if hasattr(option_type, \"_pydantic_type\"):\n                source_type = option_type._pydantic_type  # type: ignore\n            else:\n                source_type = cast(type, option_type)\n            if isinstance(data, source_type):\n                return _convert_from_pydantic_to_strawberry_type(\n                    option_type, data_from_model=data, extra=extra\n                )\n    if isinstance(type_, EnumDefinition):\n        return data\n    if isinstance(type_, StrawberryList):\n        items = []\n        for index, item in enumerate(data):\n            items.append(\n                _convert_from_pydantic_to_strawberry_type(\n                    type_.of_type,\n                    data_from_model=item,\n                    extra=extra[index] if extra else None,\n                )\n            )\n\n        return items\n\n    if hasattr(type_, \"_type_definition\"):\n        # in the case of an interface, the concrete type may be more specific\n        # than the type in the field definition\n        # don't check _strawberry_input_type because inputs can't be interfaces\n        if hasattr(type(data), \"_strawberry_type\"):\n            type_ = type(data)._strawberry_type\n        return convert_pydantic_model_to_strawberry_class(\n            type_, model_instance=data_from_model, extra=extra\n        )\n\n    return data\n\n\ndef convert_pydantic_model_to_strawberry_class(cls, *, model_instance=None, extra=None):\n    extra = extra or {}\n    kwargs = {}\n\n    for field in cls._type_definition.fields:\n        field = cast(StrawberryField, field)\n        python_name = field.python_name\n\n        data_from_extra = extra.get(python_name, None)\n        data_from_model = (\n            getattr(model_instance, python_name, None) if model_instance else None\n        )\n\n        # only convert and add fields to kwargs if they are present in the `__init__`\n        # method of the class\n        if field.init:\n            kwargs[python_name] = _convert_from_pydantic_to_strawberry_type(\n                field.type, data_from_model, extra=data_from_extra\n            )\n\n    return cls(**kwargs)\n", "path": "strawberry/experimental/pydantic/conversion.py"}, {"content": "from __future__ import annotations\n\nimport builtins\nimport dataclasses\nimport warnings\nfrom functools import partial\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    List,\n    Optional,\n    Sequence,\n    Type,\n    cast,\n)\n\nfrom pydantic import BaseModel\nfrom pydantic.fields import ModelField\nfrom typing_extensions import Literal\n\nfrom graphql import GraphQLResolveInfo\n\nimport strawberry\nfrom strawberry.arguments import UNSET\nfrom strawberry.experimental.pydantic.conversion import (\n    convert_pydantic_model_to_strawberry_class,\n)\nfrom strawberry.experimental.pydantic.fields import get_basic_type\nfrom strawberry.experimental.pydantic.utils import (\n    DataclassCreationFields,\n    ensure_all_auto_fields_in_pydantic,\n    get_default_factory_for_field,\n    get_private_fields,\n    sort_creation_fields,\n)\nfrom strawberry.field import StrawberryField\nfrom strawberry.object_type import _process_type, _wrap_dataclass\nfrom strawberry.schema_directive import StrawberrySchemaDirective\nfrom strawberry.types.type_resolver import _get_fields\nfrom strawberry.types.types import TypeDefinition\n\nfrom .exceptions import MissingFieldsListError, UnregisteredTypeException\n\n\ndef replace_pydantic_types(type_: Any, is_input: bool):\n    origin = getattr(type_, \"__origin__\", None)\n    if origin is Literal:\n        # Literal does not have types in its __args__ so we return early\n        return type_\n    if hasattr(type_, \"__args__\"):\n        replaced_type = type_.copy_with(\n            tuple(replace_pydantic_types(t, is_input) for t in type_.__args__)\n        )\n\n        if isinstance(replaced_type, TypeDefinition):\n            # TODO: Not sure if this is necessary. No coverage in tests\n            # TODO: Unnecessary with StrawberryObject\n\n            replaced_type = builtins.type(\n                replaced_type.name,\n                (),\n                {\"_type_definition\": replaced_type},\n            )\n\n        return replaced_type\n\n    if issubclass(type_, BaseModel):\n        attr = \"_strawberry_input_type\" if is_input else \"_strawberry_type\"\n        if hasattr(type_, attr):\n            return getattr(type_, attr)\n        else:\n            raise UnregisteredTypeException(type_)\n\n    return type_\n\n\ndef get_type_for_field(field: ModelField, is_input: bool):\n    type_ = field.outer_type_\n    type_ = get_basic_type(type_)\n    type_ = replace_pydantic_types(type_, is_input)\n\n    if not field.required:\n        type_ = Optional[type_]\n\n    return type_\n\n\nif TYPE_CHECKING:\n    from strawberry.experimental.pydantic.conversion_types import (\n        PydanticModel,\n        StrawberryTypeFromPydantic,\n    )\n\n\ndef type(\n    model: Type[PydanticModel],\n    *,\n    fields: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    is_input: bool = False,\n    is_interface: bool = False,\n    description: Optional[str] = None,\n    directives: Optional[Sequence[StrawberrySchemaDirective]] = (),\n    all_fields: bool = False,\n) -> Callable[..., Type[StrawberryTypeFromPydantic[PydanticModel]]]:\n    def wrap(cls: Any) -> Type[StrawberryTypeFromPydantic[PydanticModel]]:\n        model_fields = model.__fields__\n        fields_set = set(fields) if fields else set([])\n\n        if fields:\n            warnings.warn(\n                \"`fields` is deprecated, use `auto` type annotations instead\",\n                DeprecationWarning,\n            )\n\n        existing_fields = getattr(cls, \"__annotations__\", {})\n        fields_set = fields_set.union(\n            set(name for name, typ in existing_fields.items() if typ is strawberry.auto)\n        )\n\n        if all_fields:\n            if fields_set:\n                warnings.warn(\n                    \"Using all_fields overrides any explicitly defined fields \"\n                    \"in the model, using both is likely a bug\",\n                    stacklevel=2,\n                )\n            fields_set = set(model_fields.keys())\n\n        if not fields_set:\n            raise MissingFieldsListError(cls)\n\n        ensure_all_auto_fields_in_pydantic(\n            model=model, auto_fields=fields_set, cls_name=cls.__name__\n        )\n\n        all_model_fields: List[DataclassCreationFields] = [\n            DataclassCreationFields(\n                name=field_name,\n                type_annotation=get_type_for_field(field, is_input),\n                field=StrawberryField(\n                    python_name=field.name,\n                    graphql_name=field.alias if field.has_alias else None,\n                    # always unset because we use default_factory instead\n                    default=UNSET,\n                    default_factory=get_default_factory_for_field(field),\n                    type_annotation=get_type_for_field(field, is_input),\n                    description=field.field_info.description,\n                ),\n            )\n            for field_name, field in model_fields.items()\n            if field_name in fields_set\n        ]\n\n        wrapped = _wrap_dataclass(cls)\n        extra_fields = cast(List[dataclasses.Field], _get_fields(wrapped))\n        private_fields = get_private_fields(wrapped)\n\n        all_model_fields.extend(\n            (\n                DataclassCreationFields(\n                    name=field.name,\n                    type_annotation=field.type,\n                    field=field,\n                )\n                for field in extra_fields + private_fields\n                if field.type != strawberry.auto\n            )\n        )\n\n        # Sort fields so that fields with missing defaults go first\n        sorted_fields = sort_creation_fields(all_model_fields)\n\n        # Implicitly define `is_type_of` to support interfaces/unions that use\n        # pydantic objects (not the corresponding strawberry type)\n        @classmethod  # type: ignore\n        def is_type_of(cls: Type, obj: Any, _info: GraphQLResolveInfo) -> bool:\n            return isinstance(obj, (cls, model))\n\n        cls = dataclasses.make_dataclass(\n            cls.__name__,\n            [field.to_tuple() for field in sorted_fields],\n            bases=cls.__bases__,\n            namespace={\"is_type_of\": is_type_of},\n        )\n\n        _process_type(\n            cls,\n            name=name,\n            is_input=is_input,\n            is_interface=is_interface,\n            description=description,\n            directives=directives,\n        )\n\n        if is_input:\n            model._strawberry_input_type = cls  # type: ignore\n        else:\n            model._strawberry_type = cls  # type: ignore\n        cls._pydantic_type = model  # type: ignore\n\n        def from_pydantic(\n            instance: PydanticModel, extra: Dict[str, Any] = None\n        ) -> StrawberryTypeFromPydantic[PydanticModel]:\n            return convert_pydantic_model_to_strawberry_class(\n                cls=cls, model_instance=instance, extra=extra\n            )\n\n        def to_pydantic(self) -> PydanticModel:\n            instance_kwargs = dataclasses.asdict(self)\n\n            return model(**instance_kwargs)\n\n        cls.from_pydantic = staticmethod(from_pydantic)\n        cls.to_pydantic = to_pydantic\n\n        return cls\n\n    return wrap\n\n\ninput = partial(type, is_input=True)\n\ninterface = partial(type, is_interface=True)\n", "path": "strawberry/experimental/pydantic/object_type.py"}]}