Search code examples
pythondjangodjango-models

Python django model not pulling the table name, returning the project name instead


I have created both a django and a python project directory structure is

 analysis
        db_router
        models
        settings
        urls
        wsgi
        settings
    compareTemplates
        apps
        models
        tests
        utils
        views

My model looks like this

class Plans(models.Model):
    PROJECT_NAME = models.TextField()

class Meta:
    db_table = 'schema.table'  # specify the schema and table name
    managed = False  # Prevent Django from managing the table schema

def __str__(self):
    return self.PROJECT_NAME

I have the database set up properly in the settings file and I am trying to see if my model can connect to it

I ran:
python manage.py shell
from compareTemplate.models import Plans
print(Plans._meta.db_table)

the value returned is "compareTemplate_plans" I was not expecting that, I was looking for "schema.Table"

This is my first real app in django, but I cannot figure out why the result is the project name.

Thanks


Solution

  • You need to define the Meta class inside the Plans model, so:

    class Plans(models.Model):
        PROJECT_NAME = models.TextField()
    
        class Meta:  # 🖘 inside the Plans class
            db_table = 'schema.table'  # specify the schema and table name
            managed = False  # Prevent Django from managing the table schema
    
        def __str__(self):
            return self.PROJECT_NAME

    Note: Normally a Django model is given a singular name [django-antipatterns], so Plan instead of Plans.