Can I make the class name to be a variable in python?

Question:

Can I make the class name to be a variable in the newer python release?

I mean can I short the following instructions to be briefer?

 if target == "course":
    return Course.objects.all()[start:end]`
 elif target == "Subject":
    return Subject.objects.all()[start:end]
 elif target == "Teacher":
    return Teacher.objects.all()[start:end]

to be briefer:

 return VARIABLE.objects.all()[start:end]
Asked By: Alston

||

Answers:

Use a dictionary:

classes = {
    'course': Course,
    'subject': Subject,
    'teacher': Teacher
}

...
    return classes[target].objects.all()[start:end]
Answered By: Tim Roberts

This looks like the Django ORM. If you’re working in a Django application there is a better way:

from django.apps import apps

Model = apps.get_model(app_label="myapp", model_name=target)

The model_name is case-insensitive. Here’s a shortcut for the same thing:

Model = apps.get_model(f"myapp.{target}")

One big advantage here is that the model name is passed around as a string, so there will not be circular import problems due to imported model classes creating circular dependencies within your package, or app initialization problems due to model classes being imported too early.

The timing of model imports is sensitive in Django applications, as pointed out in docs:

The application registry is initialized in three stages. At each stage, Django processes all applications in the order of INSTALLED_APPS.

First Django imports each item in INSTALLED_APPS.

If it’s an application configuration class, Django imports the root package of the application, defined by its name attribute. If it’s a Python package, Django looks for an application configuration in an apps.py submodule, or else creates a default application configuration.

At this stage, your code shouldn’t import any models!

In other words, your applications’ root packages and the modules that define your application configuration classes shouldn’t import any models, even indirectly.

Strictly speaking, Django allows importing models once their application configuration is loaded. However, in order to avoid needless constraints on the order of INSTALLED_APPS, it’s strongly recommended not import any models at this stage.

Answered By: wim
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.