How to use schema with variable to pass though different environnement

I try to variabilise schema name because i use different environnment for my project. So i do this in my models.py:

    # 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"

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 make my migration --> noproblem

then when i migrate i got this error :

./manage.py migrate Applications
Operations to perform:
  Apply all migrations: Applications
Running migrations:
  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 "."
LINE 1: ...ons_applicationdjango" RENAME TO "applications_db"."Applicat...
                                                             ^

i try several things but it dont work. I hope that i can variablise schema name :/

Thanks for the help

Your error message suggests that the backslash in your database table name is causing the issue. You seem to be trying to escape the double quotes. So you should rename db_table = f'{schema}.\"ApplicationDjango\"'to:

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

Get rid of the backslashes and use the double quotes to enclose the db_table value and see if that fixes your issue.

Вернуться на верх