2

I am trying to have two tables in one database like below based on development and production environment.

  • development dev_my_comments
  • production my_comments

I tried using environment variable while declaring table like below

class Data_Comments(models.Model):
    class Status(models.IntegerChoices):
        GENERAL = 0
        YELLOW = 1
        RED = 2
    ord_no = models.ForeignKey(Data_Import, on_delete=models.CASCADE, related_name='comments')
    comment = models.CharField(max_length=500, null=True)
    strike_comment_type =  models.IntegerField(choices=Status.choices, default=0)
    strike_date = models.DateTimeField(auto_now=True, blank=True)
    updated_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='comments_user')

    class Meta:
        db_table = 'my_comments' if settings.ENV_TYPE == 'PRO' else 'dev_my_comments'
        app_label = "my_app"

by using this option, make migrations just renames existing tables instead of creating new... (wanted to have both the tables and want to migrate changes on both tables)

is there something I am missing to make it work?

Praveen
  • 346
  • 1
  • 6
  • 18
  • Good question. I was thinking about it but I don't find the answer. I know it's not the same but would you solve your problem using two different databases? Like this: https://stackoverflow.com/questions/60709408/how-to-make-django-use-two-different-databases-based-on-debug-flag – LaCharcaSoftware Mar 23 '22 at 16:43

2 Answers2

0

I don't think that would work... because Django will create migration files and the value for db_table will be assigned to dev_my_comments. And your production will have the dev_my_comments as your table name as well.

I've not seen this pattern for naming tables, is there any reason you have to share the DB but name the table differently between dev & prod?

PatDuJour
  • 893
  • 1
  • 10
  • 25
-1

I don't think it's a good idea. Anyway you can pass db_table as a constant and django will use the variable for the migrations.

db_table = TABLE_NAME

note* you can't change it after running migrate tho.

Ziad Ahmed
  • 74
  • 7
  • Yes, I know this solution which is already mentioned in my question... in Flask there is an option db = SQLAlchemy(app) db.create_all() this will create if table not exits.... .... do we have anything like this in Django?? – Praveen Mar 23 '22 at 19:36