Andrew Barr
Andrew Barr

Reputation: 3800

programatically accessing Django models from another app

I have a moderately complicated Django project with a variety of different apps (app1, app2 etc), each with their own models. I am building a MetaApp app to track info about each app, with a MetaApp class in models.py, and fields such as appname and modelname

MetaApp drives an index view that summarizes various aspects of each project. I would like to include a count of the database records for each app. This means that I need to programmatically access models from other apps. If I I know the appname and modelname, how do I programmatically access these models?

projects = MetaApp.objects.all()
projects[0].appname[0].modelname.ojects.all()

This code results in an attribute error, because I am storing the appname and modelname as unicode strings. What is the workaround?

Upvotes: 0

Views: 1106

Answers (1)

catavaran
catavaran

Reputation: 45555

Use the django.db.models.loading.get_model() function:

from django.db.models.loading import get_model

model = get_model(app_name, model_name)
object_list = model.objects.all()

Upvotes: 3

Related Questions