Reputation: 8757
I create a new Django app (not project) called Bussinesses, then add following class to the models.py
.
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)
If I use Bussinesses directly, the Django will access the "bussinesses_bussinesses" table in the database, which obviously does not exist.
Because the table "bussinesses" is also used by another APP, So can't rename it. I want to know how to use the Django model without using table prefix, and I don't want to use the raw database API directly.
Upvotes: 27
Views: 25860
Reputation: 9037
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 ):
...
Upvotes: 12
Reputation: 14735
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.
Upvotes: 59
Reputation: 22007
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.
Upvotes: 2
Reputation: 767
you can actually set the table name manually using the meta class, more here: https://docs.djangoproject.com/en/dev/ref/models/options/
Upvotes: 1