116

Given a model's instance object, how can I get the database table's name?

I don't want to specify names explicitly in the Meta class.

Mathieu Rodic
  • 6,637
  • 2
  • 43
  • 49
Ber
  • 40,356
  • 16
  • 72
  • 88

1 Answers1

198

Found the answer myself: the _meta attribute of an instance has the information:

model_instance._meta.db_table
Ber
  • 40,356
  • 16
  • 72
  • 88
  • this is quite weird that Model's table name accessible from protected attribute `_meta::Options` – Alex-Bogdanov May 14 '18 at 09:25
  • 7
    @Alex-Bogdanov: the `_meta` property is not protected. It is a documented part of the public API. It is prefixed with the leading underscore to avoid conflicts with names that people may actually want to use on their models. – Ryan Hiebert Jun 26 '18 at 14:47
  • 2
    If you would like to, create a property method to return it... `@property` `def table_name(self):` `return self._meta.db_table` – Jcc.Sanabria Sep 12 '18 at 23:16