7

I would like to retrieve the Model object while knowing the table_name

For ex:

class User(models.Model):
    class Meta:
        db_table = 'my_users_table'

Are there ways that return User by taking my_users_table as input?

nehem
  • 12,775
  • 6
  • 58
  • 84

2 Answers2

12

I would like to retrieve the Model object

I think you mean the Model class here instead of object.

One possible solution that I can think of is to get all the models and match for db_table:

from django.apps import apps
model = next((m for m in apps.get_models() if m._meta.db_table=='my_users_table'), None)

If there is no model with the given db_table name then the model will be None.

AKS
  • 18,983
  • 3
  • 43
  • 54
2

I don't think there is a direct way to do this. But you can create your own function which will do this for you.

Based on https://stackoverflow.com/a/29739109/3627387

from django.apps import apps

def get_model_by_db_table(db_table):
    for model in apps.get_models():
        if model._meta.db_table == db_table:
            return model
    else:
        # here you can do fallback logic if no model with db_table found
        raise ValueError('No model found with db_table {}!'.format(db_table))
        # or return None

Or you can do this using ContentType model

Edit:

The link provided for ContentType is broken. This may be tried instead.

Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63