In django models, how to make all table names not have the app label?
I have a database that was already being used by other applications before i began writing a web interface with django for it. The table names follow simple naming standards, so the django model Customer should m开发者_StackOverflowap to the table "customer" in the db. At the same time I'm adding new tables/models. Since I find it cumbersome to use app_customer every time i have to write a query (django's ORM is definitely not enough for them) in the other applications and I don't want to rename the existing tables, what is the best way to make all models in my django app use tables without applabel_, besides adding a Meta class with db_table= to each model?
Is there any reason why I shouldn't do this? I have only one web app that needs to access this db, everything else doesn't use django models.
You can add a Meta
class in your model class and within it specified your table name as db_table
.
In the Django Document:
class Meta:
db_table = 'my_author_table'
This might work (I haven't tested it)
class CustomModel(Model):
def __init__(self, *args, **kwargs):
self._meta.db_table = self.__class_.__name__.lower()
super(CustomModel, self).__init__(*args, **kwargs)
And then you inherit all your models from CustomModel. Although I'm not sure it's worth the trouble, just to avoid specifying it in Meta.
精彩评论