开发者

Django syncdb custom name for table

manage.py syncdb creates db tables for the models in form appname_modelname.How can i make manage.py to create tables in the format just modelname?

开发者_JS百科

is the only way is to add class Meta: db_table = u'modelname'


Yes, the only way to change the name of the created table is to set db_table to the inner Meta class.

See https://docs.djangoproject.com/en/dev/ref/models/options/#table-names.


However, with some metaclass magic, it is actually possible to do what you are looking for. This example is just to show that it is possible since Python is such a nice language. It can break with newer releases (even though unlikely) of Django since ModelBase and _meta is not officially documented AFAIK. I would just stick with adding db_table manually in your models.

By creating a custom metaclass that constructs the model classes it is possible to change the db_table attribute on the inner meta class.

from django.db import models
from django.db.models.base import ModelBase

class ModelWithoutAppNameBase(ModelBase):
    def __new__(cls, name, bases, attrs):
        model = super(ModelWithoutAppNameBase, cls).__new__(cls, name, bases, attrs)
        model._meta.db_table = name.lower()
        return model


class ModelWithoutAppName(models.Model):
    __metaclass__ = ModelWithoutAppNameBase

You then inherit from ModelWithoutAppName instead of django.db.models.Model when you create your models:

class YourModel(ModelWithoutAppName):  # database table name will be yourmodel
   foo = models.IntegerField()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜