51

I have a model and have a model manager for this model. I'm writing some sql in the model manager, and I need the table name of the model in sql. I know the name of table is combined by metadata app_label and db_name, but is it possible that I can access them from manager class? I know I can create an model instance in the manager, but I would rather not do that..

Thanks very much!

odieatla
  • 1,049
  • 3
  • 15
  • 35
  • Only tangentially related to the original question (and the various methods in the answers), but if `_meta.db_table` is giving you a relation-does-not-exist error, you may have a mixed-case app or table name, and may need quotes around the table name. See https://stackoverflow.com/questions/55297807/when-do-postgres-column-or-table-names-need-quotes-and-when-dont-they or – Sarah Messer Nov 07 '22 at 21:29

3 Answers3

70

Model manager has the field model:

Model.objects.model._meta.db_table
erthalion
  • 3,094
  • 2
  • 21
  • 28
14

For a given instance, you can use instance._meta.db_table but that also works for the model class too, so if you can step up from the manager to its model, that'll work too

Steve Jalim
  • 11,989
  • 1
  • 37
  • 54
11

Let's say you have a model named Service

You can use

Service._meta.db_table # this will work too

This as well

Service.objects.model._meta.db_table # this will work too

This as well
Let's say you had an instance of the service Model like this

service = Service.objects.get(pk=1)
# get table name like this
table_name = service._meta.db_table # this will work too
Koushik Das
  • 9,678
  • 3
  • 51
  • 50