AttributeError
pydantic.errors.AttributeError: 'BaseModel' object has no attribute 'model_fields'
Stack trace
AttributeError: 'BaseModel' object has no attribute 'model_fields'
File "app.py", line 42, in parse_output
fields = MyModel.model_fields
File "/usr/local/lib/python3.9/site-packages/pydantic/main.py", line 341, in __getattr__
raise AttributeError(f"'BaseModel' object has no attribute '{item}'") Why it happens
Pydantic v2 introduced 'model_fields' to replace 'model.__fields__' from v1. Code using 'model_fields' will fail on Pydantic v1 because that attribute does not exist. This mismatch causes AttributeError when accessing model schema fields.
Detection
Add version checks or try/except around 'model_fields' access to detect compatibility issues early, and log Pydantic version at startup for monitoring.
Causes & fixes
Code uses 'model_fields' attribute introduced in Pydantic v2 but runs with Pydantic v1 installed.
Replace all 'model_fields' references with 'model.__fields__' when running on Pydantic v1, or upgrade Pydantic to v2.
Mixed environment where some dependencies expect Pydantic v2 but the runtime has v1 installed.
Ensure consistent Pydantic version across all dependencies and runtime by pinning Pydantic to v2 in your environment.
Using third-party libraries or LangChain versions that require Pydantic v2 but your project uses v1.
Upgrade your project and dependencies to support Pydantic v2 or downgrade those libraries to versions compatible with Pydantic v1.
Code: broken vs fixed
from pydantic import BaseModel
class MyModel(BaseModel):
name: str
# This line triggers AttributeError on Pydantic v1
fields = MyModel.model_fields # broken line
print(fields) import os
from pydantic import BaseModel
import pydantic
class MyModel(BaseModel):
name: str
# Fix: Use model_fields if Pydantic v2, else __fields__ for v1
if pydantic.VERSION.startswith('2'):
fields = MyModel.model_fields
else:
fields = MyModel.__fields__
print(fields) # fixed code Workaround
Wrap access to 'model_fields' in try/except AttributeError and fallback to '__fields__' to handle both Pydantic versions dynamically.
Prevention
Standardize on Pydantic v2 for all code and dependencies, and audit your codebase for deprecated v1 attributes to avoid compatibility issues.