Created
February 15, 2024 10:49
-
-
Save gboeer/1f2f50e87a1e42573247185d1c1da04b to your computer and use it in GitHub Desktop.
Retrieve a field from a pydantic BaseModel which just has the given name or has the name set as an alias
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional | |
from pydantic import BaseModel | |
def get_model_field(model: BaseModel, field_name: str) -> Optional[str]: | |
""" | |
Retrieves the field name from a Pydantic model based on a given field name or alias. | |
This function searches the model's fields to find a match for the given field name or alias. | |
If a match is found, it returns the actual field name. Since pydantic allows using | |
the same alias for different fields, this function also checks for ambiguities, | |
i.e., whether the given name or alias corresponds to multiple fields. | |
In such cases, it raises a ValueError to indicate the ambiguity. | |
""" | |
id_fields = [ | |
name | |
for name, field in model.model_fields.items() | |
if field_name in (name, field.alias) | |
] | |
# pydantic allows the same alias for different fields | |
if len(id_fields) > 1: | |
raise ValueError("Ambiguous field '{field_name}' in model: {model}") | |
return id_fields[0] if len(id_fields) else None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment