Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: get table name of a model in the model manager?

Tags:

django

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!

like image 427
odieatla Avatar asked May 01 '14 08:05

odieatla


People also ask

What is __ Str__ in Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this. Note: how objects are just plainly numbered. to this.

Is there a list field for Django models?

Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json. In Django 1.10 and above, there's a new ArrayField field you can use.

What is Verbose_name in Django?

verbose_name is a human-readable name for the field. If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces. This attribute in general changes the field name in admin interface. Syntax – field_name = models.Field(verbose_name = "name")

How do I find models in Django?

In Django 1.7+ it is better to use get_model() on the Django app registry, which is available via django. apps. apps. get_model(model_name) .


3 Answers

Model manager has the field model:

Model.objects.model._meta.db_table
like image 148
erthalion Avatar answered Oct 19 '22 06:10

erthalion


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

like image 44
Steve Jalim Avatar answered Oct 19 '22 07:10

Steve Jalim


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
like image 6
Koushik Das Avatar answered Oct 19 '22 07:10

Koushik Das