[Django]-Django: How does it find the User model?

3👍

Well you define models in the models.py file of an app. So that means that the module in which you stored the model class is app.models. Therefore the import reads:

from app.models import MyModel

Django has in essence nothing to do with this: this is how Python loads modules and classes from these module(s).

Django however loads – when you for example run the server – the apps that are located in the INSTALLED_APPS list of the settings file (usually settings.py), and thus constructs a “register” where it stores Django models, and it names them in a uniform way: app_name.ModelName. There is no reason to specify models here, since models are defined in models.py, and it thus would only introduce “noise”.

You can obtain a reference to the model class with apps.get_model [Django-doc]

from django.apps import apps

apps.get_model('app_name', 'ModelName')

It thus then checks the registers of the loaded models, and returns a reference to the model.

Linking through a string is useful (and sometimes required) when there is cyclic referencing. For example if you have two models A and B, and A refers to BandBthroughA(for example withForeignKeys), then one of the two models is defined first. This means that if you defineAfirst, it can not refer to theB` class itself, since at that point it does not yet exists. In Django, one then specifies the model through a string. The Django system will then first load the models, and then “tie the knot“: resolve the references by replacing the strings with a reference to the actual model class.

Leave a comment