Repository: koxudaxi/datamodel-code-generator

Issue:
Unnecessary `_aliased` suffix added to models generated from GraphQL union types
**Describe the bug**

When using a union in GraphQL, an unnecessary `_aliased` suffix is added.

```python
class GroupMetadata(BaseModel):
    name: String
    typename__: Optional[Literal['GroupMetadata']] = Field(
        'GroupMetadata', alias='__typename'
    )


class Resource(BaseModel):
    metadata: UserMetadata_aliased
    typename__: Optional[Literal['Resource']] = Field('Resource', alias='__typename')


class UserMetadata(BaseModel):
    name: String
    typename__: Optional[Literal['UserMetadata']] = Field(
        'UserMetadata', alias='__typename'
    )


Metadata: TypeAlias = Union[
    'GroupMetadata',
    'UserMetadata',
]
```

**To Reproduce**

Example schema:

```graphql
type GroupMetadata {
    name: String!
}

type UserMetadata {
    name: String!
}

union Metadata = UserMetadata | GroupMetadata

type Resource {
    metadata: UserMetadata!
}
```

Used commandline:
```
$ poetry run datamodel-codegen --input ./test.graphqls --input-file-type graphql --output ./test.py
```

**Expected behavior**

```python
class GroupMetadata(BaseModel):
    name: String
    typename__: Optional[Literal['GroupMetadata']] = Field(
        'GroupMetadata', alias='__typename'
    )


class Resource(BaseModel):
    metadata: UserMetadata
    typename__: Optional[Literal['Resource']] = Field('Resource', alias='__typename')


class UserMetadata(BaseModel):
    name: String
    typename__: Optional[Literal['UserMetadata']] = Field(
        'UserMetadata', alias='__typename'
    )


Metadata: TypeAlias = Union[
    'GroupMetadata',
    'UserMetadata',
]
```

**Version:**
 - OS: MacOS 15.4.1
 - Python version: 3.12.1
 - datamodel-code-generator version: v0.30.0

**Additional context**

I discovered this issue when upgrading datamodel-code-generator from v0.28.5 to v0.30.0.

I confirmed that when the `union Metadata = UserMetadata | GroupMetadata` line is removed from the GraphQL schema, the generated Python code does not include the `_aliased` suffix, as shown below:

```graphql
type GroupMetadata {
    name: String!
}

type UserMetadata {
    name: String!
}

type Resource {
    metadata: UserMetadata!
}
```


Discussion:
+1 , I see this percolating to base types, leading to some pydantic models to have some `float` fields typed as `float_aliased` which is not a valid type in Python.
PR welcome 👍 



Patch:
diff --git a/src/datamodel_code_generator/parser/base.py b/src/datamodel_code_generator/parser/base.py
index 74df98e54..098ceea49 100644
--- a/src/datamodel_code_generator/parser/base.py
+++ b/src/datamodel_code_generator/parser/base.py
@@ -1202,7 +1202,10 @@ def __alias_shadowed_imports(  # noqa: PLR6301
     ) -> None:
         for model in models:
             for model_field in model.fields:
-                if model_field.data_type.type in all_model_field_names:
+                if (
+                    model_field.data_type.type in all_model_field_names
+                    and model_field.data_type.type == model_field.name
+                ):
                     alias = model_field.data_type.type + "_aliased"
                     model_field.data_type.type = alias
                     if model_field.data_type.import_:  # pragma: no cover


Test patch:
diff --git a/tests/data/expected/parser/graphql/union-aliased-bug.py b/tests/data/expected/parser/graphql/union-aliased-bug.py
new file mode 100644
index 000000000..096b9f9fb
--- /dev/null
+++ b/tests/data/expected/parser/graphql/union-aliased-bug.py
@@ -0,0 +1,45 @@
+# generated by datamodel-codegen:
+#   filename:  union-aliased-bug.graphql
+#   timestamp: 2019-07-26T00:00:00+00:00
+
+from __future__ import annotations
+
+from typing import Literal, Optional, TypeAlias, Union
+
+from pydantic import BaseModel, Field
+
+Boolean: TypeAlias = bool
+"""
+The `Boolean` scalar type represents `true` or `false`.
+"""
+
+
+String: TypeAlias = str
+"""
+The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
+"""
+
+
+class GroupMetadata(BaseModel):
+    name: String
+    typename__: Optional[Literal['GroupMetadata']] = Field(
+        'GroupMetadata', alias='__typename'
+    )
+
+
+class Resource(BaseModel):
+    metadata: UserMetadata
+    typename__: Optional[Literal['Resource']] = Field('Resource', alias='__typename')
+
+
+class UserMetadata(BaseModel):
+    name: String
+    typename__: Optional[Literal['UserMetadata']] = Field(
+        'UserMetadata', alias='__typename'
+    )
+
+
+Metadata: TypeAlias = Union[
+    'GroupMetadata',
+    'UserMetadata',
+]
diff --git a/tests/data/graphql/union-aliased-bug.graphql b/tests/data/graphql/union-aliased-bug.graphql
new file mode 100644
index 000000000..27812859b
--- /dev/null
+++ b/tests/data/graphql/union-aliased-bug.graphql
@@ -0,0 +1,13 @@
+type GroupMetadata {
+  name: String!
+}
+
+type UserMetadata {
+  name: String!
+}
+
+union Metadata = UserMetadata | GroupMetadata
+
+type Resource {
+  metadata: UserMetadata!
+}
diff --git a/tests/parser/test_graphql.py b/tests/parser/test_graphql.py
index 5d8d5e7b8..f3e6df565 100644
--- a/tests/parser/test_graphql.py
+++ b/tests/parser/test_graphql.py
@@ -27,3 +27,23 @@ def test_graphql_field_enum() -> None:
         ])
         assert return_code == Exit.OK
         assert output_file.read_text() == (EXPECTED_GRAPHQL_PATH / "field-default-enum.py").read_text()
+
+
+@freeze_time("2019-07-26")
+def test_graphql_union_aliased_bug() -> None:
+    with TemporaryDirectory() as output_dir:
+        output_file: Path = Path(output_dir) / "output.py"
+        return_code: Exit = main([
+            "--input",
+            str(GRAPHQL_DATA_PATH / "union-aliased-bug.graphql"),
+            "--output",
+            str(output_file),
+            "--input-file-type",
+            "graphql",
+        ])
+        assert return_code == Exit.OK
+        actual = output_file.read_text().rstrip()
+        expected = (EXPECTED_GRAPHQL_PATH / "union-aliased-bug.py").read_text().rstrip()
+        if actual != expected:
+            pass
+        assert actual == expected