Python – Django: How does it find the user model?

Django: How does it find the user model?… here is a solution to the problem.

Django: How does it find the user model?

I have a question about AUTH_USER_MODEL in Django:
https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model

The default value is auth. User。 However, the actual model is in auth.models.User. How does Django find the right class?

I asked because when you use models in Django, you write from myapp.models import MyModel. So why don’t I need auth. The models in User are used for AUTH_USER_MODEL?

Can someone explain or show me the code that uses it?

Solution

Then you define the file of the model app in models.py. So this means that the module in which you store the model class is app.models

from app.models import MyModel

Django is inherently unrelated to this: this is how Python loads modules and classes from these modules.

However, Django

loads – for example, when you run the server – a list of application settings files (usually settings.py) located in the INSTALLED_APPS, constructing a “register” that stores Django models and naming them in a uniform way: app_name. There is no reason to specify models here, as models are defined in models.py, so only “noise” is introduced.

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

from django.apps import apps

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

It then checks the registers that load the model and returns a reference to the model.

Chaining via strings is useful (and sometimes necessary) when circular references are present. For example, if you have two models, A and B, and A refers to B and B through (for example with foreign keys s), then one of the two models is defined first. This means that if you define first, it can not refer to the B’ class itself, because it didn’t exist yet. In Django, then specify the model by string. The Django system will then load the model first, and then “tie the knot“: resolve the reference by replacing the string with a reference to the actual model class.

Related Problems and Solutions