You can retrieve Django models by their model name using the apps.get_model
method. Here is an example:
from django.apps import apps
# Retrieve the model class for the given app_label and model_name
my_model = apps.get_model(app_label='myapp', model_name='MyModel')
# Query the database for all instances of the model
my_objects = my_model.objects.all()
# Print the results
for obj in my_objects:
print(obj)
In this example, we use apps.get_model
to retrieve the MyModel
class from the myapp
app. We then use the objects
manager of the model to query the database and retrieve all instances of the model. Finally, we loop through the results and print them.
Asked: 2021-06-21 11:00:00 +0000
Seen: 9 times
Last updated: Jun 26 '21