47 lines
1.6 KiB
Python
47 lines
1.6 KiB
Python
"""Base model class with automatic registry registration."""
|
|
|
|
from backend.core.database_registry import registry
|
|
|
|
|
|
class BaseModel:
|
|
"""
|
|
Base model mixin that automatically registers models with the registry.
|
|
|
|
All models should inherit from both this class and Base.
|
|
"""
|
|
|
|
def __init_subclass__(cls, **kwargs):
|
|
"""Automatically register model when subclass is created."""
|
|
super().__init_subclass__(**kwargs)
|
|
|
|
# Only register if the class has a __tablename__
|
|
if hasattr(cls, '__tablename__'):
|
|
# Register with the registry to prevent duplicate definitions
|
|
registered_model = registry.register_model(cls)
|
|
|
|
# If a different model was already registered for this table,
|
|
# update the class to use the registered one
|
|
if registered_model is not cls:
|
|
# Copy attributes from registered model
|
|
for key, value in registered_model.__dict__.items():
|
|
if not key.startswith('_'):
|
|
setattr(cls, key, value)
|
|
|
|
|
|
def create_model_base():
|
|
"""
|
|
Create a base class for all models that combines SQLAlchemy Base and registry.
|
|
|
|
Returns:
|
|
A base class that all models should inherit from
|
|
"""
|
|
# Create a new base class that combines BaseModel with the registry's Base
|
|
class Model(BaseModel, registry.Base):
|
|
"""Base class for all database models."""
|
|
__abstract__ = True
|
|
|
|
return Model
|
|
|
|
|
|
# Create the model base class
|
|
Model = create_model_base() |