We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
` --use-default-kwarg` breaks codegen with default_factory `Field(default=default_factory=...`
**Describe the bug**
When using ` --use-default-kwarg` on models with a default_factory codegen breaks:  `Field(default=default_factory=...`


```
File "src\black\parsing.py", line 127, in lib2to3_parse
black.parsing.InvalidInput: Cannot parse: 17:54:     foo: Optional[Foo] = Field(default=default_factory=lambda :Foo.parse_obj({'foo': 'foo'}), title='Foo')
```
**To Reproduce**

Example schema:
```json

{
    "title": "Requests",
    "definitions": {
        "Foo": {
            "title": "Foo",
            "type": "object",
            "properties": {
                "foo": {
                    "title": "Foo",
                    "default": "foo",
                    "type": "string"
                }
            }
        },
        "Bar": {
            "title": "Bar",
            "type": "object",
            "properties": {
                "foo": {
                    "title": "Foo",
                    "default": {
                        "foo": "foo"
                    },
                    "allOf": [
                        {
                            "$ref": "#/definitions/Foo"
                        }
                    ]
                }
            }
        }
    }
}

```

Used commandline:
```
$ datamodel-codegen --input schema.json --output model.py --use-default-kwarg
```

**Expected behavior**
Such a model should be produced
``` python
class Foo(BaseModel):
    foo: Optional[str] = Field(default='foo', title='Foo')


class Bar(BaseModel):
    foo: Optional[Foo] = Field(default_factory=lambda: Foo.parse_obj({'foo': 'foo'}), title='Foo')

```

**Version:**

✅ works in 0.16.1
❌ breaks in 0.17.0 (probably introduced by https://github.com/koxudaxi/datamodel-code-generator/pull/1047 )
- python 3.11.1
- windows 11

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `datamodel_code_generator/model/pydantic/base_model.py`
Content:
```
1 from __future__ import annotations
2 
3 from pathlib import Path
4 from typing import Any, ClassVar, DefaultDict, Dict, List, Optional, Set, Tuple, Union
5 
6 from pydantic import Field
7 
8 from datamodel_code_generator import cached_property
9 from datamodel_code_generator.imports import Import
10 from datamodel_code_generator.model import (
11     ConstraintsBase,
12     DataModel,
13     DataModelFieldBase,
14 )
15 from datamodel_code_generator.model.base import UNDEFINED
16 from datamodel_code_generator.model.pydantic.imports import IMPORT_EXTRA, IMPORT_FIELD
17 from datamodel_code_generator.reference import Reference
18 from datamodel_code_generator.types import chain_as_tuple
19 
20 
21 class Constraints(ConstraintsBase):
22     gt: Optional[Union[float, int]] = Field(None, alias='exclusiveMinimum')
23     ge: Optional[Union[float, int]] = Field(None, alias='minimum')
24     lt: Optional[Union[float, int]] = Field(None, alias='exclusiveMaximum')
25     le: Optional[Union[float, int]] = Field(None, alias='maximum')
26     multiple_of: Optional[float] = Field(None, alias='multipleOf')
27     min_items: Optional[int] = Field(None, alias='minItems')
28     max_items: Optional[int] = Field(None, alias='maxItems')
29     min_length: Optional[int] = Field(None, alias='minLength')
30     max_length: Optional[int] = Field(None, alias='maxLength')
31     regex: Optional[str] = Field(None, alias='pattern')
32     unique_items: Optional[bool] = Field(None, alias='uniqueItems')
33 
34 
35 class DataModelField(DataModelFieldBase):
36     _EXCLUDE_FIELD_KEYS: ClassVar[Set[str]] = {
37         'alias',
38         'default',
39         'const',
40         'gt',
41         'ge',
42         'lt',
43         'le',
44         'multiple_of',
45         'min_items',
46         'max_items',
47         'min_length',
48         'max_length',
49         'regex',
50     }
51     _COMPARE_EXPRESSIONS: ClassVar[Set[str]] = {'gt', 'ge', 'lt', 'le'}
52     constraints: Optional[Constraints] = None
53 
54     @property
55     def method(self) -> Optional[str]:
56         return self.validator
57 
58     @property
59     def validator(self) -> Optional[str]:
60         return None
61         # TODO refactor this method for other validation logic
62         # from datamodel_code_generator.model.pydantic import VALIDATOR_TEMPLATE
63         #
64         # return VALIDATOR_TEMPLATE.render(
65         #     field_name=self.name, types=','.join([t.type_hint for t in self.data_types])
66         # )
67 
68     @property
69     def field(self) -> Optional[str]:
70         """for backwards compatibility"""
71         result = str(self)
72         if self.use_default_kwarg and not result.startswith('Field(...'):
73             # Use `default=` for fields that have a default value so that type
74             # checkers using @dataclass_transform can infer the field as
75             # optional in __init__.
76             result = result.replace('Field(', 'Field(default=')
77         if result == '':
78             return None
79 
80         return result
81 
82     def self_reference(self) -> bool:
83         return isinstance(self.parent, BaseModel) and self.parent.reference.path in {
84             d.reference.path for d in self.data_type.all_data_types if d.reference
85         }
86 
87     def _get_strict_field_constraint_value(self, constraint: str, value: Any) -> Any:
88         if value is None or constraint not in self._COMPARE_EXPRESSIONS:
89             return value
90 
91         for data_type in self.data_type.all_data_types:
92             if data_type.type == 'int':
93                 value = int(value)
94             else:
95                 value = float(value)
96                 break
97         return value
98 
99     def _get_default_as_pydantic_model(self) -> Optional[str]:
100         for data_type in self.data_type.data_types or (self.data_type,):
101             # TODO: Check nested data_types
102             if data_type.is_dict or self.data_type.is_union:
103                 # TODO: Parse Union and dict model for default
104                 continue
105             elif data_type.is_list and len(data_type.data_types) == 1:
106                 data_type = data_type.data_types[0]
107                 data_type.alias
108                 if (
109                     data_type.reference
110                     and isinstance(data_type.reference.source, BaseModel)
111                     and isinstance(self.default, list)
112                 ):  # pragma: no cover
113                     return f'lambda :[{data_type.alias or data_type.reference.source.class_name}.parse_obj(v) for v in {repr(self.default)}]'
114             elif data_type.reference and isinstance(
115                 data_type.reference.source, BaseModel
116             ):  # pragma: no cover
117                 return f'lambda :{data_type.alias or data_type.reference.source.class_name}.parse_obj({repr(self.default)})'
118         return None
119 
120     def __str__(self) -> str:
121         data: Dict[str, Any] = {
122             k: v for k, v in self.extras.items() if k not in self._EXCLUDE_FIELD_KEYS
123         }
124         if self.alias:
125             data['alias'] = self.alias
126         if (
127             self.constraints is not None
128             and not self.self_reference()
129             and not self.data_type.strict
130         ):
131             data = {
132                 **data,
133                 **{
134                     k: self._get_strict_field_constraint_value(k, v)
135                     for k, v in self.constraints.dict().items()
136                 },
137             }
138 
139         if self.use_field_description:
140             data.pop('description', None)  # Description is part of field docstring
141 
142         if self.const:
143             data['const'] = True
144 
145         discriminator = data.pop('discriminator', None)
146         if discriminator:
147             if isinstance(discriminator, str):
148                 data['discriminator'] = discriminator
149             elif isinstance(discriminator, dict):  # pragma: no cover
150                 data['discriminator'] = discriminator['propertyName']
151 
152         if self.required:
153             default_factory = None
154         elif self.default and 'default_factory' not in data:
155             default_factory = self._get_default_as_pydantic_model()
156         else:
157             default_factory = data.pop('default_factory', None)
158 
159         field_arguments = sorted(
160             f'{k}={repr(v)}' for k, v in data.items() if v is not None
161         )
162 
163         if not field_arguments and not default_factory:
164             if self.nullable and self.required:
165                 return 'Field(...)'  # Field() is for mypy
166             return ''
167 
168         if self.use_annotated:
169             pass
170         elif self.required:
171             field_arguments = ['...', *field_arguments]
172         elif default_factory:
173             field_arguments = [f'default_factory={default_factory}', *field_arguments]
174         else:
175             field_arguments = [f'{repr(self.default)}', *field_arguments]
176 
177         return f'Field({", ".join(field_arguments)})'
178 
179     @property
180     def annotated(self) -> Optional[str]:
181         if not self.use_annotated or not str(self):
182             return None
183         return f'Annotated[{self.type_hint}, {str(self)}]'
184 
185 
186 class BaseModel(DataModel):
187     TEMPLATE_FILE_PATH: ClassVar[str] = 'pydantic/BaseModel.jinja2'
188     BASE_CLASS: ClassVar[str] = 'pydantic.BaseModel'
189 
190     def __init__(
191         self,
192         *,
193         reference: Reference,
194         fields: List[DataModelField],
195         decorators: Optional[List[str]] = None,
196         base_classes: Optional[List[Reference]] = None,
197         custom_base_class: Optional[str] = None,
198         custom_template_dir: Optional[Path] = None,
199         extra_template_data: Optional[DefaultDict[str, Any]] = None,
200         path: Optional[Path] = None,
201         description: Optional[str] = None,
202         default: Any = UNDEFINED,
203         nullable: bool = False,
204     ):
205         methods: List[str] = [field.method for field in fields if field.method]
206 
207         super().__init__(
208             fields=fields,  # type: ignore
209             reference=reference,
210             decorators=decorators,
211             base_classes=base_classes,
212             custom_base_class=custom_base_class,
213             custom_template_dir=custom_template_dir,
214             extra_template_data=extra_template_data,
215             methods=methods,
216             path=path,
217             description=description,
218             default=default,
219             nullable=nullable,
220         )
221 
222         config_parameters: Dict[str, Any] = {}
223 
224         additionalProperties = self.extra_template_data.get('additionalProperties')
225         allow_extra_fields = self.extra_template_data.get('allow_extra_fields')
226         if additionalProperties is not None or allow_extra_fields:
227             config_parameters['extra'] = (
228                 'Extra.allow'
229                 if additionalProperties or allow_extra_fields
230                 else 'Extra.forbid'
231             )
232             self._additional_imports.append(IMPORT_EXTRA)
233 
234         for config_attribute in 'allow_population_by_field_name', 'allow_mutation':
235             if config_attribute in self.extra_template_data:
236                 config_parameters[config_attribute] = self.extra_template_data[
237                     config_attribute
238                 ]
239         for data_type in self.all_data_types:
240             if data_type.is_custom_type:
241                 config_parameters['arbitrary_types_allowed'] = True
242                 break
243 
244         if isinstance(self.extra_template_data.get('config'), dict):
245             for key, value in self.extra_template_data['config'].items():
246                 config_parameters[key] = value
247 
248         if config_parameters:
249             from datamodel_code_generator.model.pydantic import Config
250 
251             self.extra_template_data['config'] = Config.parse_obj(config_parameters)
252 
253     @property
254     def imports(self) -> Tuple[Import, ...]:
255         if any(f for f in self.fields if f.field):
256             return chain_as_tuple(super().imports, (IMPORT_FIELD,))
257         return super().imports
258 
259     @cached_property
260     def template_file_path(self) -> Path:
261         # This property is for Backward compatibility
262         # Current version supports '{custom_template_dir}/BaseModel.jinja'
263         # But, Future version will support only '{custom_template_dir}/pydantic/BaseModel.jinja'
264         if self._custom_template_dir is not None:
265             custom_template_file_path = (
266                 self._custom_template_dir / Path(self.TEMPLATE_FILE_PATH).name
267             )
268             if custom_template_file_path.exists():
269                 return custom_template_file_path
270         return super().template_file_path
271
```
--- 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/datamodel_code_generator/model/pydantic/base_model.py b/datamodel_code_generator/model/pydantic/base_model.py
--- a/datamodel_code_generator/model/pydantic/base_model.py
+++ b/datamodel_code_generator/model/pydantic/base_model.py
@@ -69,7 +69,11 @@
     def field(self) -> Optional[str]:
         """for backwards compatibility"""
         result = str(self)
-        if self.use_default_kwarg and not result.startswith('Field(...'):
+        if (
+            self.use_default_kwarg
+            and not result.startswith('Field(...')
+            and not result.startswith('Field(default_factory=')
+        ):
             # Use `default=` for fields that have a default value so that type
             # checkers using @dataclass_transform can infer the field as
             # optional in __init__.

{"golden_diff": "diff --git a/datamodel_code_generator/model/pydantic/base_model.py b/datamodel_code_generator/model/pydantic/base_model.py\n--- a/datamodel_code_generator/model/pydantic/base_model.py\n+++ b/datamodel_code_generator/model/pydantic/base_model.py\n@@ -69,7 +69,11 @@\n     def field(self) -> Optional[str]:\n         \"\"\"for backwards compatibility\"\"\"\n         result = str(self)\n-        if self.use_default_kwarg and not result.startswith('Field(...'):\n+        if (\n+            self.use_default_kwarg\n+            and not result.startswith('Field(...')\n+            and not result.startswith('Field(default_factory=')\n+        ):\n             # Use `default=` for fields that have a default value so that type\n             # checkers using @dataclass_transform can infer the field as\n             # optional in __init__.\n", "issue": "` --use-default-kwarg` breaks codegen with default_factory `Field(default=default_factory=...`\n**Describe the bug**\r\nWhen using ` --use-default-kwarg` on models with a default_factory codegen breaks:  `Field(default=default_factory=...`\r\n\r\n\r\n```\r\nFile \"src\\black\\parsing.py\", line 127, in lib2to3_parse\r\nblack.parsing.InvalidInput: Cannot parse: 17:54:     foo: Optional[Foo] = Field(default=default_factory=lambda :Foo.parse_obj({'foo': 'foo'}), title='Foo')\r\n```\r\n**To Reproduce**\r\n\r\nExample schema:\r\n```json\r\n\r\n{\r\n    \"title\": \"Requests\",\r\n    \"definitions\": {\r\n        \"Foo\": {\r\n            \"title\": \"Foo\",\r\n            \"type\": \"object\",\r\n            \"properties\": {\r\n                \"foo\": {\r\n                    \"title\": \"Foo\",\r\n                    \"default\": \"foo\",\r\n                    \"type\": \"string\"\r\n                }\r\n            }\r\n        },\r\n        \"Bar\": {\r\n            \"title\": \"Bar\",\r\n            \"type\": \"object\",\r\n            \"properties\": {\r\n                \"foo\": {\r\n                    \"title\": \"Foo\",\r\n                    \"default\": {\r\n                        \"foo\": \"foo\"\r\n                    },\r\n                    \"allOf\": [\r\n                        {\r\n                            \"$ref\": \"#/definitions/Foo\"\r\n                        }\r\n                    ]\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n```\r\n\r\nUsed commandline:\r\n```\r\n$ datamodel-codegen --input schema.json --output model.py --use-default-kwarg\r\n```\r\n\r\n**Expected behavior**\r\nSuch a model should be produced\r\n``` python\r\nclass Foo(BaseModel):\r\n    foo: Optional[str] = Field(default='foo', title='Foo')\r\n\r\n\r\nclass Bar(BaseModel):\r\n    foo: Optional[Foo] = Field(default_factory=lambda: Foo.parse_obj({'foo': 'foo'}), title='Foo')\r\n\r\n```\r\n\r\n**Version:**\r\n\r\n\u2705 works in 0.16.1\r\n\u274c breaks in 0.17.0 (probably introduced by https://github.com/koxudaxi/datamodel-code-generator/pull/1047 )\r\n- python 3.11.1\r\n- windows 11\n", "before_files": [{"content": "from __future__ import annotations\n\nfrom pathlib import Path\nfrom typing import Any, ClassVar, DefaultDict, Dict, List, Optional, Set, Tuple, Union\n\nfrom pydantic import Field\n\nfrom datamodel_code_generator import cached_property\nfrom datamodel_code_generator.imports import Import\nfrom datamodel_code_generator.model import (\n    ConstraintsBase,\n    DataModel,\n    DataModelFieldBase,\n)\nfrom datamodel_code_generator.model.base import UNDEFINED\nfrom datamodel_code_generator.model.pydantic.imports import IMPORT_EXTRA, IMPORT_FIELD\nfrom datamodel_code_generator.reference import Reference\nfrom datamodel_code_generator.types import chain_as_tuple\n\n\nclass Constraints(ConstraintsBase):\n    gt: Optional[Union[float, int]] = Field(None, alias='exclusiveMinimum')\n    ge: Optional[Union[float, int]] = Field(None, alias='minimum')\n    lt: Optional[Union[float, int]] = Field(None, alias='exclusiveMaximum')\n    le: Optional[Union[float, int]] = Field(None, alias='maximum')\n    multiple_of: Optional[float] = Field(None, alias='multipleOf')\n    min_items: Optional[int] = Field(None, alias='minItems')\n    max_items: Optional[int] = Field(None, alias='maxItems')\n    min_length: Optional[int] = Field(None, alias='minLength')\n    max_length: Optional[int] = Field(None, alias='maxLength')\n    regex: Optional[str] = Field(None, alias='pattern')\n    unique_items: Optional[bool] = Field(None, alias='uniqueItems')\n\n\nclass DataModelField(DataModelFieldBase):\n    _EXCLUDE_FIELD_KEYS: ClassVar[Set[str]] = {\n        'alias',\n        'default',\n        'const',\n        'gt',\n        'ge',\n        'lt',\n        'le',\n        'multiple_of',\n        'min_items',\n        'max_items',\n        'min_length',\n        'max_length',\n        'regex',\n    }\n    _COMPARE_EXPRESSIONS: ClassVar[Set[str]] = {'gt', 'ge', 'lt', 'le'}\n    constraints: Optional[Constraints] = None\n\n    @property\n    def method(self) -> Optional[str]:\n        return self.validator\n\n    @property\n    def validator(self) -> Optional[str]:\n        return None\n        # TODO refactor this method for other validation logic\n        # from datamodel_code_generator.model.pydantic import VALIDATOR_TEMPLATE\n        #\n        # return VALIDATOR_TEMPLATE.render(\n        #     field_name=self.name, types=','.join([t.type_hint for t in self.data_types])\n        # )\n\n    @property\n    def field(self) -> Optional[str]:\n        \"\"\"for backwards compatibility\"\"\"\n        result = str(self)\n        if self.use_default_kwarg and not result.startswith('Field(...'):\n            # Use `default=` for fields that have a default value so that type\n            # checkers using @dataclass_transform can infer the field as\n            # optional in __init__.\n            result = result.replace('Field(', 'Field(default=')\n        if result == '':\n            return None\n\n        return result\n\n    def self_reference(self) -> bool:\n        return isinstance(self.parent, BaseModel) and self.parent.reference.path in {\n            d.reference.path for d in self.data_type.all_data_types if d.reference\n        }\n\n    def _get_strict_field_constraint_value(self, constraint: str, value: Any) -> Any:\n        if value is None or constraint not in self._COMPARE_EXPRESSIONS:\n            return value\n\n        for data_type in self.data_type.all_data_types:\n            if data_type.type == 'int':\n                value = int(value)\n            else:\n                value = float(value)\n                break\n        return value\n\n    def _get_default_as_pydantic_model(self) -> Optional[str]:\n        for data_type in self.data_type.data_types or (self.data_type,):\n            # TODO: Check nested data_types\n            if data_type.is_dict or self.data_type.is_union:\n                # TODO: Parse Union and dict model for default\n                continue\n            elif data_type.is_list and len(data_type.data_types) == 1:\n                data_type = data_type.data_types[0]\n                data_type.alias\n                if (\n                    data_type.reference\n                    and isinstance(data_type.reference.source, BaseModel)\n                    and isinstance(self.default, list)\n                ):  # pragma: no cover\n                    return f'lambda :[{data_type.alias or data_type.reference.source.class_name}.parse_obj(v) for v in {repr(self.default)}]'\n            elif data_type.reference and isinstance(\n                data_type.reference.source, BaseModel\n            ):  # pragma: no cover\n                return f'lambda :{data_type.alias or data_type.reference.source.class_name}.parse_obj({repr(self.default)})'\n        return None\n\n    def __str__(self) -> str:\n        data: Dict[str, Any] = {\n            k: v for k, v in self.extras.items() if k not in self._EXCLUDE_FIELD_KEYS\n        }\n        if self.alias:\n            data['alias'] = self.alias\n        if (\n            self.constraints is not None\n            and not self.self_reference()\n            and not self.data_type.strict\n        ):\n            data = {\n                **data,\n                **{\n                    k: self._get_strict_field_constraint_value(k, v)\n                    for k, v in self.constraints.dict().items()\n                },\n            }\n\n        if self.use_field_description:\n            data.pop('description', None)  # Description is part of field docstring\n\n        if self.const:\n            data['const'] = True\n\n        discriminator = data.pop('discriminator', None)\n        if discriminator:\n            if isinstance(discriminator, str):\n                data['discriminator'] = discriminator\n            elif isinstance(discriminator, dict):  # pragma: no cover\n                data['discriminator'] = discriminator['propertyName']\n\n        if self.required:\n            default_factory = None\n        elif self.default and 'default_factory' not in data:\n            default_factory = self._get_default_as_pydantic_model()\n        else:\n            default_factory = data.pop('default_factory', None)\n\n        field_arguments = sorted(\n            f'{k}={repr(v)}' for k, v in data.items() if v is not None\n        )\n\n        if not field_arguments and not default_factory:\n            if self.nullable and self.required:\n                return 'Field(...)'  # Field() is for mypy\n            return ''\n\n        if self.use_annotated:\n            pass\n        elif self.required:\n            field_arguments = ['...', *field_arguments]\n        elif default_factory:\n            field_arguments = [f'default_factory={default_factory}', *field_arguments]\n        else:\n            field_arguments = [f'{repr(self.default)}', *field_arguments]\n\n        return f'Field({\", \".join(field_arguments)})'\n\n    @property\n    def annotated(self) -> Optional[str]:\n        if not self.use_annotated or not str(self):\n            return None\n        return f'Annotated[{self.type_hint}, {str(self)}]'\n\n\nclass BaseModel(DataModel):\n    TEMPLATE_FILE_PATH: ClassVar[str] = 'pydantic/BaseModel.jinja2'\n    BASE_CLASS: ClassVar[str] = 'pydantic.BaseModel'\n\n    def __init__(\n        self,\n        *,\n        reference: Reference,\n        fields: List[DataModelField],\n        decorators: Optional[List[str]] = None,\n        base_classes: Optional[List[Reference]] = None,\n        custom_base_class: Optional[str] = None,\n        custom_template_dir: Optional[Path] = None,\n        extra_template_data: Optional[DefaultDict[str, Any]] = None,\n        path: Optional[Path] = None,\n        description: Optional[str] = None,\n        default: Any = UNDEFINED,\n        nullable: bool = False,\n    ):\n        methods: List[str] = [field.method for field in fields if field.method]\n\n        super().__init__(\n            fields=fields,  # type: ignore\n            reference=reference,\n            decorators=decorators,\n            base_classes=base_classes,\n            custom_base_class=custom_base_class,\n            custom_template_dir=custom_template_dir,\n            extra_template_data=extra_template_data,\n            methods=methods,\n            path=path,\n            description=description,\n            default=default,\n            nullable=nullable,\n        )\n\n        config_parameters: Dict[str, Any] = {}\n\n        additionalProperties = self.extra_template_data.get('additionalProperties')\n        allow_extra_fields = self.extra_template_data.get('allow_extra_fields')\n        if additionalProperties is not None or allow_extra_fields:\n            config_parameters['extra'] = (\n                'Extra.allow'\n                if additionalProperties or allow_extra_fields\n                else 'Extra.forbid'\n            )\n            self._additional_imports.append(IMPORT_EXTRA)\n\n        for config_attribute in 'allow_population_by_field_name', 'allow_mutation':\n            if config_attribute in self.extra_template_data:\n                config_parameters[config_attribute] = self.extra_template_data[\n                    config_attribute\n                ]\n        for data_type in self.all_data_types:\n            if data_type.is_custom_type:\n                config_parameters['arbitrary_types_allowed'] = True\n                break\n\n        if isinstance(self.extra_template_data.get('config'), dict):\n            for key, value in self.extra_template_data['config'].items():\n                config_parameters[key] = value\n\n        if config_parameters:\n            from datamodel_code_generator.model.pydantic import Config\n\n            self.extra_template_data['config'] = Config.parse_obj(config_parameters)\n\n    @property\n    def imports(self) -> Tuple[Import, ...]:\n        if any(f for f in self.fields if f.field):\n            return chain_as_tuple(super().imports, (IMPORT_FIELD,))\n        return super().imports\n\n    @cached_property\n    def template_file_path(self) -> Path:\n        # This property is for Backward compatibility\n        # Current version supports '{custom_template_dir}/BaseModel.jinja'\n        # But, Future version will support only '{custom_template_dir}/pydantic/BaseModel.jinja'\n        if self._custom_template_dir is not None:\n            custom_template_file_path = (\n                self._custom_template_dir / Path(self.TEMPLATE_FILE_PATH).name\n            )\n            if custom_template_file_path.exists():\n                return custom_template_file_path\n        return super().template_file_path\n", "path": "datamodel_code_generator/model/pydantic/base_model.py"}], "after_files": [{"content": "from __future__ import annotations\n\nfrom pathlib import Path\nfrom typing import Any, ClassVar, DefaultDict, Dict, List, Optional, Set, Tuple, Union\n\nfrom pydantic import Field\n\nfrom datamodel_code_generator import cached_property\nfrom datamodel_code_generator.imports import Import\nfrom datamodel_code_generator.model import (\n    ConstraintsBase,\n    DataModel,\n    DataModelFieldBase,\n)\nfrom datamodel_code_generator.model.base import UNDEFINED\nfrom datamodel_code_generator.model.pydantic.imports import IMPORT_EXTRA, IMPORT_FIELD\nfrom datamodel_code_generator.reference import Reference\nfrom datamodel_code_generator.types import chain_as_tuple\n\n\nclass Constraints(ConstraintsBase):\n    gt: Optional[Union[float, int]] = Field(None, alias='exclusiveMinimum')\n    ge: Optional[Union[float, int]] = Field(None, alias='minimum')\n    lt: Optional[Union[float, int]] = Field(None, alias='exclusiveMaximum')\n    le: Optional[Union[float, int]] = Field(None, alias='maximum')\n    multiple_of: Optional[float] = Field(None, alias='multipleOf')\n    min_items: Optional[int] = Field(None, alias='minItems')\n    max_items: Optional[int] = Field(None, alias='maxItems')\n    min_length: Optional[int] = Field(None, alias='minLength')\n    max_length: Optional[int] = Field(None, alias='maxLength')\n    regex: Optional[str] = Field(None, alias='pattern')\n    unique_items: Optional[bool] = Field(None, alias='uniqueItems')\n\n\nclass DataModelField(DataModelFieldBase):\n    _EXCLUDE_FIELD_KEYS: ClassVar[Set[str]] = {\n        'alias',\n        'default',\n        'const',\n        'gt',\n        'ge',\n        'lt',\n        'le',\n        'multiple_of',\n        'min_items',\n        'max_items',\n        'min_length',\n        'max_length',\n        'regex',\n    }\n    _COMPARE_EXPRESSIONS: ClassVar[Set[str]] = {'gt', 'ge', 'lt', 'le'}\n    constraints: Optional[Constraints] = None\n\n    @property\n    def method(self) -> Optional[str]:\n        return self.validator\n\n    @property\n    def validator(self) -> Optional[str]:\n        return None\n        # TODO refactor this method for other validation logic\n        # from datamodel_code_generator.model.pydantic import VALIDATOR_TEMPLATE\n        #\n        # return VALIDATOR_TEMPLATE.render(\n        #     field_name=self.name, types=','.join([t.type_hint for t in self.data_types])\n        # )\n\n    @property\n    def field(self) -> Optional[str]:\n        \"\"\"for backwards compatibility\"\"\"\n        result = str(self)\n        if (\n            self.use_default_kwarg\n            and not result.startswith('Field(...')\n            and not result.startswith('Field(default_factory=')\n        ):\n            # Use `default=` for fields that have a default value so that type\n            # checkers using @dataclass_transform can infer the field as\n            # optional in __init__.\n            result = result.replace('Field(', 'Field(default=')\n        if result == '':\n            return None\n\n        return result\n\n    def self_reference(self) -> bool:\n        return isinstance(self.parent, BaseModel) and self.parent.reference.path in {\n            d.reference.path for d in self.data_type.all_data_types if d.reference\n        }\n\n    def _get_strict_field_constraint_value(self, constraint: str, value: Any) -> Any:\n        if value is None or constraint not in self._COMPARE_EXPRESSIONS:\n            return value\n\n        for data_type in self.data_type.all_data_types:\n            if data_type.type == 'int':\n                value = int(value)\n            else:\n                value = float(value)\n                break\n        return value\n\n    def _get_default_as_pydantic_model(self) -> Optional[str]:\n        for data_type in self.data_type.data_types or (self.data_type,):\n            # TODO: Check nested data_types\n            if data_type.is_dict or self.data_type.is_union:\n                # TODO: Parse Union and dict model for default\n                continue\n            elif data_type.is_list and len(data_type.data_types) == 1:\n                data_type = data_type.data_types[0]\n                data_type.alias\n                if (\n                    data_type.reference\n                    and isinstance(data_type.reference.source, BaseModel)\n                    and isinstance(self.default, list)\n                ):  # pragma: no cover\n                    return f'lambda :[{data_type.alias or data_type.reference.source.class_name}.parse_obj(v) for v in {repr(self.default)}]'\n            elif data_type.reference and isinstance(\n                data_type.reference.source, BaseModel\n            ):  # pragma: no cover\n                return f'lambda :{data_type.alias or data_type.reference.source.class_name}.parse_obj({repr(self.default)})'\n        return None\n\n    def __str__(self) -> str:\n        data: Dict[str, Any] = {\n            k: v for k, v in self.extras.items() if k not in self._EXCLUDE_FIELD_KEYS\n        }\n        if self.alias:\n            data['alias'] = self.alias\n        if (\n            self.constraints is not None\n            and not self.self_reference()\n            and not self.data_type.strict\n        ):\n            data = {\n                **data,\n                **{\n                    k: self._get_strict_field_constraint_value(k, v)\n                    for k, v in self.constraints.dict().items()\n                },\n            }\n\n        if self.use_field_description:\n            data.pop('description', None)  # Description is part of field docstring\n\n        if self.const:\n            data['const'] = True\n\n        discriminator = data.pop('discriminator', None)\n        if discriminator:\n            if isinstance(discriminator, str):\n                data['discriminator'] = discriminator\n            elif isinstance(discriminator, dict):  # pragma: no cover\n                data['discriminator'] = discriminator['propertyName']\n\n        if self.required:\n            default_factory = None\n        elif self.default and 'default_factory' not in data:\n            default_factory = self._get_default_as_pydantic_model()\n        else:\n            default_factory = data.pop('default_factory', None)\n\n        field_arguments = sorted(\n            f'{k}={repr(v)}' for k, v in data.items() if v is not None\n        )\n\n        if not field_arguments and not default_factory:\n            if self.nullable and self.required:\n                return 'Field(...)'  # Field() is for mypy\n            return ''\n\n        if self.use_annotated:\n            pass\n        elif self.required:\n            field_arguments = ['...', *field_arguments]\n        elif default_factory:\n            field_arguments = [f'default_factory={default_factory}', *field_arguments]\n        else:\n            field_arguments = [f'{repr(self.default)}', *field_arguments]\n\n        return f'Field({\", \".join(field_arguments)})'\n\n    @property\n    def annotated(self) -> Optional[str]:\n        if not self.use_annotated or not str(self):\n            return None\n        return f'Annotated[{self.type_hint}, {str(self)}]'\n\n\nclass BaseModel(DataModel):\n    TEMPLATE_FILE_PATH: ClassVar[str] = 'pydantic/BaseModel.jinja2'\n    BASE_CLASS: ClassVar[str] = 'pydantic.BaseModel'\n\n    def __init__(\n        self,\n        *,\n        reference: Reference,\n        fields: List[DataModelField],\n        decorators: Optional[List[str]] = None,\n        base_classes: Optional[List[Reference]] = None,\n        custom_base_class: Optional[str] = None,\n        custom_template_dir: Optional[Path] = None,\n        extra_template_data: Optional[DefaultDict[str, Any]] = None,\n        path: Optional[Path] = None,\n        description: Optional[str] = None,\n        default: Any = UNDEFINED,\n        nullable: bool = False,\n    ):\n        methods: List[str] = [field.method for field in fields if field.method]\n\n        super().__init__(\n            fields=fields,  # type: ignore\n            reference=reference,\n            decorators=decorators,\n            base_classes=base_classes,\n            custom_base_class=custom_base_class,\n            custom_template_dir=custom_template_dir,\n            extra_template_data=extra_template_data,\n            methods=methods,\n            path=path,\n            description=description,\n            default=default,\n            nullable=nullable,\n        )\n\n        config_parameters: Dict[str, Any] = {}\n\n        additionalProperties = self.extra_template_data.get('additionalProperties')\n        allow_extra_fields = self.extra_template_data.get('allow_extra_fields')\n        if additionalProperties is not None or allow_extra_fields:\n            config_parameters['extra'] = (\n                'Extra.allow'\n                if additionalProperties or allow_extra_fields\n                else 'Extra.forbid'\n            )\n            self._additional_imports.append(IMPORT_EXTRA)\n\n        for config_attribute in 'allow_population_by_field_name', 'allow_mutation':\n            if config_attribute in self.extra_template_data:\n                config_parameters[config_attribute] = self.extra_template_data[\n                    config_attribute\n                ]\n        for data_type in self.all_data_types:\n            if data_type.is_custom_type:\n                config_parameters['arbitrary_types_allowed'] = True\n                break\n\n        if isinstance(self.extra_template_data.get('config'), dict):\n            for key, value in self.extra_template_data['config'].items():\n                config_parameters[key] = value\n\n        if config_parameters:\n            from datamodel_code_generator.model.pydantic import Config\n\n            self.extra_template_data['config'] = Config.parse_obj(config_parameters)\n\n    @property\n    def imports(self) -> Tuple[Import, ...]:\n        if any(f for f in self.fields if f.field):\n            return chain_as_tuple(super().imports, (IMPORT_FIELD,))\n        return super().imports\n\n    @cached_property\n    def template_file_path(self) -> Path:\n        # This property is for Backward compatibility\n        # Current version supports '{custom_template_dir}/BaseModel.jinja'\n        # But, Future version will support only '{custom_template_dir}/pydantic/BaseModel.jinja'\n        if self._custom_template_dir is not None:\n            custom_template_file_path = (\n                self._custom_template_dir / Path(self.TEMPLATE_FILE_PATH).name\n            )\n            if custom_template_file_path.exists():\n                return custom_template_file_path\n        return super().template_file_path\n", "path": "datamodel_code_generator/model/pydantic/base_model.py"}]}