[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.

๐Ÿ‘คpztrick

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

๐Ÿ‘คmawimawi

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