[Django]-Django 1.7 โ€“ model discovery and application configs with custom app label

3๐Ÿ‘

โœ…

I rewiewed most part of Django code deeply. Models in applications which have custom app label defined in the app config, as it is given in the question, are not being imported by Django. This is because, even you change the label in app config, models app_label is not changed. So, Django thinks, models and the custom app configs are for different application. I think, this is a bug.

In django.apps.registry, there is lines in populate method which is:

...
            # Load models.
            for app_config in self.app_configs.values():
                all_models = self.all_models[app_config.label]
                app_config.import_models(all_models)
...

This part should also import models in modules defined in app_config.name, not just for app_config.label.Cause, there are not gonna be models with app label same with the app config label. This is one of the problematic parts which causes the issue. This is not enough, changing models app_label somehow is also needed.

Solution:

Here is my workaround.

I have an abstract app config which all of my app configs are gonna be inherited from.

from collections import OrderedDict
from django.apps import AppConfig, apps


class BaseAppConfig(AppConfig):
    def __init__(self, *args, **kwargs):
        super(BaseAppConfig, self).__init__(*args, **kwargs)
        # Also import the models in modules defined in self.name
        mod_path, _, cls_name = self.name.rpartition('.')
        self.import_models(OrderedDict([(k, v) for k, v in apps.all_models[cls_name].iteritems() if self.name in v.__module__]))


    def import_models(self, all_models):
        if not self.models:
            # Set the model app_labels as self.label
            for m in all_models.values():
                m._meta.app_label = self.label
            super(BaseAppConfig, self).import_models(all_models)

This is a workaround not to touch Django code. But, I think this issue must be resolved in Django. Models app_labels should also change by the app_label value defined in the app config.

๐Ÿ‘คAhmet DAL

Leave a comment