flask_crud_app/definitions/models.py

45 lines
1.6 KiB
Python
Raw Normal View History

2025-01-29 05:27:19 +00:00
from flask_sqlalchemy import SQLAlchemy
2025-02-11 20:45:25 +00:00
from config import item_attributes # Import the configuration
from sqlalchemy import Enum, Integer, String, Date, Column
2025-02-12 22:53:02 +00:00
from config import sql_conf
2025-01-29 05:27:19 +00:00
db = SQLAlchemy()
2025-02-11 20:45:25 +00:00
# Dynamically create the Asset model
def create_asset_model():
"""
Dynamically creates the Asset model based on the configuration in item_attributes.
"""
attrs = {
2025-02-12 22:53:02 +00:00
'__tablename__': sql_conf.SQL_TABLE, # Table name
2025-02-11 20:45:25 +00:00
'__init__': lambda self, **kwargs: self.__dict__.update(kwargs), # Constructor
'__repr__': lambda self: f"<Asset {getattr(self, next(attrib for attrib, config in item_attributes.items() if config.primary))}>" # Representation
}
2025-01-29 05:27:19 +00:00
2025-02-11 20:45:25 +00:00
for attrib, config in item_attributes.items():
# Determine the column type based on the configuration
if config.html_input_type == "text":
column_type = String(50)
elif config.html_input_type == "date":
column_type = Date
elif config.html_input_type == "select":
column_type = Enum(*config.options)
elif config.html_input_type == "number":
column_type = Integer
2025-01-29 10:05:36 +00:00
2025-02-11 20:45:25 +00:00
# Define the column with additional properties
attrs[attrib] = Column(
column_type,
primary_key=config.primary,
unique=config.unique,
nullable=not config.required,
default=config.default_val,
comment=config.comment
)
2025-01-29 10:05:36 +00:00
2025-02-11 20:45:25 +00:00
# Create the Asset class dynamically
Asset = type('Asset', (db.Model,), attrs)
return Asset
2025-01-29 10:05:36 +00:00
2025-02-11 20:45:25 +00:00
# Create the Asset model
Asset = create_asset_model()