# Error on migrate using postgresql schema

**URL:** <https://forum.djangoproject.com/t/error-on-migrate-using-postgresql-schema/41111>\
**Category:** Using Django\
**Created:** [May 26, 2025, 12:38pm UTC](https://forum.djangoproject.com/t/error-on-migrate-using-postgresql-schema/41111 "2025-05-26T12:38:46Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Maverik37](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/maverik37/32/12255_2.png) [@Maverik37](https://forum.djangoproject.com/u/Maverik37)\
**Post date:** [May 26, 2025, 12:38pm UTC](https://forum.djangoproject.com/t/error-on-migrate-using-postgresql-schema/41111/1 "2025-05-26T12:38:46Z")

</div>

Hi all

I’m working on a django project in which i set 3 environment : DEV,VIP,PROD.

So i add a variable in my settings that detect in which environment i am and then i use it in models to change dynamically the schema name to use.

To do that i write this in the **models.py** :

```auto
from django.db import models
# from django.contrib.auth.models import AbstractUser 
from django.contrib.auth.models import AbstractUser
#Pour plus d'information sur le fonctionnement des models : https://docs.djangoproject.com/fr/5.1/topics/db/models/
from django.conf import settings

if settings.ENV == "DEV":
    schema="applications_db"
elif settings.ENV == "VIP":
    schema="applications_vip_db"
elif settings.ENV == "PROD":
    schema="applications_prod_db"

```

and then in my class models i write this :

```auto
class ApplicationDjango(models.Model):
    a_name = models.CharField(max_length=100,verbose_name="Nom")
    a_portail_name = models.CharField(max_length=100,verbose_name="Nom portail")
    a_views_name = models.CharField(max_length=100,verbose_name="Views name")
    a_url_home = models.CharField(max_length=100,verbose_name="Url home")

    def __str__ (self):
        return self.a_name+"_"+self.a_portail_name
    #class pour ajouter une contrainte d'unicité
    class Meta:
        managed= True
        db_table = f"{schema}.'ApplicationDjango'"

```

I havent got any problems when running the makemigrations that give me this in my migration file:

```auto
# Generated by Django 4.2.15 on 2025-05-26 13:16

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('Applications', '0003_alter_applicationdjango_table_alter_user_table'),
    ]

    operations = [
        migrations.AlterModelTable(
            name='applicationdjango',
            table="applications_db.'ApplicationDjango'",
        ),
        migrations.AlterModelTable(
            name='user',
            table='"applications_db"."User" ',
        ),
    ]

```

But i have this error when i try to migrate :

```auto
Applying Applications.0004_alter_applicationdjango_table_alter_user_table...Traceback (most recent call last):
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute
    return self.cursor.execute(sql)
psycopg2.errors.UndefinedTable: relation "Applications_applicationdjango" does not exist

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/livraison/toto/DJANGOPROJET/./manage.py", line 22, in <module>
    main()
  File "/opt/livraison/toto/DJANGOPROJET/./manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/toto/.local/lib/python3.9/site-packages/django/core/management/ __init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "/home/toto/.local/lib/python3.9/site-packages/django/core/management/ __init__.py", line 436, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/toto/.local/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/toto/.local/lib/python3.9/site-packages/django/core/management/base.py", line 458, in execute
    output = self.handle(*args, **options)
  File "/home/toto/.local/lib/python3.9/site-packages/django/core/management/base.py", line 106, in wrapper
    res = handle_func(*args, **kwargs)
  File "/home/toto/.local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 356, in handle
    post_migrate_state = executor.migrate(
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 135, in migrate
    state = self._migrate_all_forwards(
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards
    state = self.apply_migration(
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 252, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/migrations/migration.py", line 132, in apply
    operation.database_forwards(
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 559, in database_forwards
    schema_editor.alter_db_table(
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 627, in alter_db_table
    self.execute(
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/backends/postgresql/schema.py", line 48, in execute
    return super().execute(sql, None)
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 201, in execute
    cursor.execute(sql, params)
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 102, in execute
    return super().execute(sql, params)
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/toto/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute
    return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "Applications_applicationdjango" does not exist

```

it seem that it sear a the table but in lowercase instead of ApplicationDjango, how can i solve it ?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [May 26, 2025, 1:27pm UTC](https://forum.djangoproject.com/t/error-on-migrate-using-postgresql-schema/41111/2 "2025-05-26T13:27:14Z")

</div>

If you want to use a case-sensitive table name, it must be enclosed by double-quotes. Using single-quotes does not work.

See [PostgreSQL: Documentation: 17: 4.1.&nbsp;Lexical Structure](https://www.postgresql.org/docs/17/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS)

---

<div class="post-metadata">

**Author:** ![Maverik37](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/maverik37/32/12255_2.png) [@Maverik37](https://forum.djangoproject.com/u/Maverik37)\
**Post date:** [May 27, 2025, 7:04am UTC](https://forum.djangoproject.com/t/error-on-migrate-using-postgresql-schema/41111/3 "2025-05-27T07:04:47Z")

</div>

Ok so i change db\_table to this :

```auto
db_table = f'{schema}."ApplicationDjango"'

```

so now in my migration file i have this :

```auto
migrations.AlterModelTable(
     name='applicationdjango',
     table='applications_db."ApplicationDjango"',

```

and now when i try to apply the migration :

```auto
Applying Applications.0004_alter_applicationdjango_table_alter_user_table...Traceback (most recent call last):
  File "/home/webadmin/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute
    return self.cursor.execute(sql)
psycopg2.errors.SyntaxError: syntax error at or near "ApplicationDjango"
LINE 1: ...ns_applicationdjango" RENAME TO "applications_db."Applicatio...

 File "/home/webadmin/.local/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/webadmin/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute
    return self.cursor.execute(sql)
django.db.utils.ProgrammingError: syntax error at or near "ApplicationDjango"
LINE 1: ...ns_applicationdjango" RENAME TO "applications_db."Applicatio...

```

☹

---

<div class="post-metadata">

**Author:** ![sevdog](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sevdog/32/20692_2.png) [@sevdog](https://forum.djangoproject.com/u/sevdog)\
**Post date:** [May 27, 2025, 9:08am UTC](https://forum.djangoproject.com/t/error-on-migrate-using-postgresql-schema/41111/4 "2025-05-27T09:08:52Z")

</div>

A part of the problem is that your `models.py` changes with the environment and thus the migration engine detects it and tries to “fix it”.

I would recommend to read this other topic which covers a similar use-case:

> [@How to have multiple PostgreSQL Schema in Django?](https://forum.djangoproject.com/t/how-to-have-multiple-postgresql-schema-in-django/20653):
>
> Hello Django lovers, I need to separate my application data into multiple Postgresql schemas. I’m trying to have a simple solution for that. So we have a new database backend which was inherited from the Django PostgreSQL backend \_cursor is replaced to be able to add SET search\_path=[schema\_name] to queries. here is a sample code: from django.db.backends.postgresql import base class DatabaseWrapper(base.DatabaseWrapper): def \_cursor(self, name=None): cursor = super().\_cursor(nam…

---

<div class="post-metadata">

**Author:** ![Maverik37](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/maverik37/32/12255_2.png) [@Maverik37](https://forum.djangoproject.com/u/Maverik37)\
**Post date:** [May 27, 2025, 9:46am UTC](https://forum.djangoproject.com/t/error-on-migrate-using-postgresql-schema/41111/5 "2025-05-27T09:46:50Z")

</div>

i havent have problem with my schema before i variabilise. all my schema are in the search path.  
the problème i have its with the variable “schema”.

The goal of it is to avoid manual modification from “applications\_db” to “applications\_vip\_db” on the models.py

did i need to override something ?

---

<div class="post-metadata">

**Author:** ![sevdog](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sevdog/32/20692_2.png) [@sevdog](https://forum.djangoproject.com/u/sevdog)\
**Post date:** [May 27, 2025, 10:08am UTC](https://forum.djangoproject.com/t/error-on-migrate-using-postgresql-schema/41111/6 "2025-05-27T10:08:44Z")

</div>

Whenever `Meta.db_table` changes the migration framework will detect it as a change in your model and will attempt to write a migration to address to it.

The simpliest way to handle it is to just change the DB connection configuration according to your environment. In this way the models are not altered and thus no migration is issued when you change environment. In other words: the logic to change schema should be in your settings file and not in your models.

see also [https://stackoverflow.com/a/74056139/30169297](https://stackoverflow.com/a/74056139/30169297)

---

<div class="post-metadata">

**Author:** ![boxed](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/boxed/32/11975_2.png) [@boxed](https://forum.djangoproject.com/u/boxed)\
**Post date:** [May 27, 2025, 1:50pm UTC](https://forum.djangoproject.com/t/error-on-migrate-using-postgresql-schema/41111/7 "2025-05-27T13:50:02Z")

</div>

My recommendation would be to not do this. It’s a bad idea and not supported by Django.

Setting the `NAME` parameter in `DATABASES`/`default` works fine though, that’s probably what you want to do.
