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?
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?
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
.
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.