Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django syncdb custom name for table

Tags:

django

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?

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

like image 779
Jibin Avatar asked Sep 21 '11 09:09

Jibin


1 Answers

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()
like image 165
andreaspelme Avatar answered Oct 18 '22 12:10

andreaspelme