Opened 15 years ago

Closed 15 years ago

#12781 closed (duplicate)

model object should offer a way to get the table name

Reported by: sienkiew Owned by: nobody
Component: Database layer (models, ORM) Version: 1.1
Severity: Keywords: enhancment request
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

If you want to make a direct SQL query, you need to know the table name, but the table name can be changed in various ways by the models.py file and the django database layer.

You can find the name of the table by

name = model_object._meta.db_table

but that _ in the name indicates a private field that is not intended for the application to use. It would be nice to have an approved way to get the table name, so I could say, for example:

cursor.execute("SELECT DISTINCT colname FROM %s" % model_object.get_table_name() )

I would not prefer to just write the table name in the SQL because my models.py file overrides the table names so that we can have multiple independent developers share the same debug database server. That is, we use something like:

class model_object( models.Model ) :
    class Meta :
        db_table = local_config.developer_name + '_model_object'

to ensure that the tables have distinct names.

The obvious workaround is:

class model_object( models.Model ) :
    @classmethod
    def get_table_name( cls ) :
        return cls._meta.db_table

I think this would work if you put this workaround in class ModelBase or class Model in django/db/models/base.py . I'm not entirely sure why there is a distinction between ModelBase and Model, so I can't present an actual patch, but I think this is close enough to check the "has patch" box below. It is, of course, subject to some architectural review too.

Change History (1)

comment:1 by Alex Gaynor, 15 years ago

Resolution: duplicate
Status: newclosed

Closing as a duplicate of #12782, which covers the larger issue here.

Note: See TracTickets for help on using tickets.
Back to Top