Ask Your Question
0

How to retrieve Django models using their model name?

asked 2021-06-21 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-06-26 08:00:00 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-06-21 11:00:00 +0000

Seen: 9 times

Last updated: Jun 26 '21