Skip to content

Instantly share code, notes, and snippets.

@gboeer
Created February 15, 2024 10:49
Show Gist options
  • Save gboeer/1f2f50e87a1e42573247185d1c1da04b to your computer and use it in GitHub Desktop.
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
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