🏗️ Automatically prefix table_names with app_label

This commit is contained in:
Brian Wiborg 2025-10-02 14:30:53 +02:00
parent c411a9795c
commit 64e98f9f0a
No known key found for this signature in database

View file

@ -34,6 +34,23 @@ class ModelMeta(type(TortoiseModel)):
# Grab the Schema class for further processing. # Grab the Schema class for further processing.
schema_opts = attrs.get("Schema", None) schema_opts = attrs.get("Schema", None)
# Create or get the inner Meta class
meta = attrs.get("Meta", type("Meta", (), {}))
# Infer app name from module if not explicitly set
if not hasattr(meta, "app"):
module = attrs.get("__module__", "")
module_parts = module.split(".")
if module_parts[-1] == "models":
inferred_app = module_parts[-2]
else:
inferred_app = module_parts[-1]
meta.app = inferred_app
# Prefix table name if not explicitly set
if not hasattr(meta, "table"):
meta.table = f"{meta.app}_{name.lower()}"
# Let Tortoise's Metaclass do it's thing. # Let Tortoise's Metaclass do it's thing.
new_cls = super().__new__(mcls, name, bases, attrs) new_cls = super().__new__(mcls, name, bases, attrs)