[Fixed]-Database table names with Django

43👍

Use the Meta class (documentation here) inside your models.py model definition:

class Aerodrome(models.Model):
    Name = models.CharField(max_length=48)
    Latitude = models.DecimalField(decimal_places=4, max_digits=7)
    Longitude = models.DecimalField(decimal_places=4, max_digits=7)

    class Meta:
        db_table = 'AERODROMES'

This will override the default naming scheme for model tables in the SQL database.


You can also add the managed attribute to control whether or not python manage.py syncdb and python manage.py flush manage the table.

class Aerodrome(models.Model):
    # ...

    class Meta:
        db_table = 'AERODROMES'
        managed = False

With this you can syncdb without fear of wiping your data.

4👍

from the django docs:
It is strongly advised that you use lowercase table names when you override the table name via db_table, particularly if you are using the MySQL backend. See the MySQL notes for more details.

https://docs.djangoproject.com/en/1.11/ref/databases/#table-names

1👍

Specifying table name for your model explicitly should help:

from django.db import models

class Aerodrome(models.Model):
    Name = models.CharField(max_length=48)
    Latitude = models.DecimalField(decimal_places=4, max_digits=7)
    Longitude = models.DecimalField(decimal_places=4, max_digits=7)

    class Meta:
        db_table = 'AERODROMES'
👤alecxe

1👍

You can set the db table name in models Meta class. as

class Aerodrome(models.Model):
    Name = models.CharField(max_length=48)
    Latitude = models.DecimalField(decimal_places=4, max_digits=7)
    Longitude = models.DecimalField(decimal_places=4, max_digits=7)

    class Meta:
        db_table="AERODROMES"

If you are prepopulating table externally. take care the data is appropriate/compatible in each record/field.

However, you have to syncdb as other tables required for django are created.

👤Rohan

Leave a comment