Skip to content Skip to sidebar Skip to footer

Database Table Names With Django

I already have a database named 'mydb', where I have a table called 'AERODROME'. My models.py looks like this: from django.db import models class Aerodrome(models.Model): Name

Solution 1:

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.

classAerodrome(models.Model):
    # ...classMeta:
        db_table = 'AERODROMES'
        managed = False

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

Solution 2:

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

Solution 3:

Specifying table name for your model explicitly should help:

from django.db import models

classAerodrome(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)

    classMeta:
        db_table = 'AERODROMES'

Solution 4:

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

classAerodrome(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.

Post a Comment for "Database Table Names With Django"