0

If I have a Django (1.6) model, I can find out its database table name with MyModel._meta.db_table.

Is there any way to do the reverse?

I could do it an ugly way, for instance by hardcoding a large dictionary of all the tables we have to all the models we have, but people won't remember to keep it updated.

If there is no direct way, is there a way to get a list of all the models in the models.pys of the currently installed apps so I can dynamically build that dictionary?

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79

2 Answers2

2

Use the django.db.models.get_models() function:

from django.db import models

db_table = 'auth_user'    
mlist = [model for model in models.get_models(include_auto_created=True)
               if model._meta.db_table == db_table]
model = mlist[0] if mlist else None
catavaran
  • 44,703
  • 8
  • 98
  • 85
1

Each model knows its own table and keeps that in Model._meta.db_table. You can combine that with my answer here to get all the models, so it looks like:

from django.db.models import get_models
models = get_models(include_auto_created=True)
table_dict = {model._meta.db_table:model for model in models}
Community
  • 1
  • 1
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895