54

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!

1
  • 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 stackoverflow.com/questions/55297807/… or Commented Nov 7, 2022 at 21:29

3 Answers 3

77

Model manager has the field model:

Model.objects.model._meta.db_table
2
  • 10
    Why not just Model._meta.db_table ? Commented Feb 13, 2022 at 18:31
  • 1
    Pycharm annoying me because Access to a protected member _meta of a class
    – Fathy
    Commented Aug 13, 2023 at 18:57
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

12

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.