Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving the Model object using table name

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?

like image 501
nehem Avatar asked Jun 08 '16 04:06

nehem


1 Answers

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.

like image 102
AKS Avatar answered Nov 05 '22 20:11

AKS