How to remove the prefix of a table for a Django model?

You can specify the table name in the model's Meta class, using the db_table property.

Also, if you're using a database table that already exists, you might also want to take a look at the managed property. After setting a model to unmanaged syncdb will not affect it (if you reset your app, for instance), but you can still use Django's ORM normally.


Just use the model meta options.

class Bussinesses(models.Model):
    business_email = models.EmailField()
    password = models.CharField(max_length=20)
    contact_first_name = models.CharField(max_length=30)
    contact_last_name = models.CharField(max_length=30)

    class Meta:
        db_table = "bussinesses"

BTW businesses is misspelled. Since you're specifying the name of the table you don't have to give your model the same name as the table, so if the table name is misspelled and you can't easily fix it, you can at least change the name of your class to the proper spelling of businesses. I would also get rid of the pluralization, and make it class Business. Finally it's not uncommon when using Django or Rails on an existing database to need to set a custom table name for every table.


As an aside, if you want to change (or remove) the prefix for all tables you can provide your own meta-class. This is useful if you have multiple cases like Businesses where you'd just like the class and table name to be the same.

For instance the following code prefixes all tables with FOO_ instead of appname_:

class MyModelBase( ModelBase ):
    def __new__( cls, name, bases, attrs, **kwargs ):
        if name != "MyModel":
            class MetaB:
                db_table = "FOO_" + name

            attrs["Meta"] = MetaB

        r = super().__new__( cls, name, bases, attrs, **kwargs )
        return r       

class MyModel( Model, metaclass = MyModelBase ):
    class Meta:
        abstract = True

class Businesses( MyModel ):
    ...

Tags:

Django

Model