|
| 1 | +from django.apps import apps |
| 2 | +from django.core.checks import Info, register |
| 3 | +from django.db import models |
| 4 | + |
| 5 | +from content_editor.models import PluginBase |
| 6 | + |
| 7 | + |
| 8 | +@register() |
| 9 | +def check_plugin_bases(app_configs, **kwargs): |
| 10 | + """ |
| 11 | + Check for unexpected non-abstract base classes in plugin models. |
| 12 | +
|
| 13 | + This check helps identify potential issues where plugin models inherit from |
| 14 | + non-abstract base classes (other than the expected PluginBase), which can |
| 15 | + lead to unexpected database table structures and relationships. |
| 16 | + """ |
| 17 | + infos = [] |
| 18 | + |
| 19 | + # Get all models from the specified app_configs or all apps |
| 20 | + if app_configs is None: |
| 21 | + models_to_check = apps.get_models() |
| 22 | + else: |
| 23 | + models_to_check = [] |
| 24 | + for app_config in app_configs: |
| 25 | + models_to_check.extend(app_config.get_models()) |
| 26 | + |
| 27 | + for model in models_to_check: |
| 28 | + # Skip proxy models - they're expected to have non-abstract parents |
| 29 | + if model._meta.proxy: |
| 30 | + continue |
| 31 | + |
| 32 | + # Check if this model inherits from PluginBase |
| 33 | + if not issubclass(model, PluginBase): |
| 34 | + continue |
| 35 | + |
| 36 | + # Check for non-abstract base classes |
| 37 | + non_abstract_bases = [ |
| 38 | + base |
| 39 | + for base in model.__bases__ |
| 40 | + if (issubclass(base, models.Model) and not base._meta.abstract) |
| 41 | + ] |
| 42 | + |
| 43 | + if non_abstract_bases: |
| 44 | + infos.append( |
| 45 | + Info( |
| 46 | + f"Found unexpected non-abstract base classes when creating {model.__module__}.{model.__qualname__}", |
| 47 | + hint=f"The following base classes are non-abstract: {', '.join(f'{base.__module__}.{base.__qualname__}' for base in non_abstract_bases)}. " |
| 48 | + "Consider making them abstract by adding 'class Meta: abstract = True'.", |
| 49 | + obj=model, |
| 50 | + id="content_editor.I001", |
| 51 | + ) |
| 52 | + ) |
| 53 | + |
| 54 | + return infos |
0 commit comments