Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
Editing models.py file and migrating changes to database in the same python code

I am looking to edit a models.py file for an app, and then migrate the changes to the database (postgreSQL) in the same python code.

In the view definition that is supposed to perform this, I am doing the following:

  1. Open models.py
  2. Append the new table's model to the existing models
  3. Close models.py
  4. Run makemigrations
  5. Run sqlmigrate
  6. Run migrate

It works fine up to Step no.3. The new table's model is being added to models.py, but 'makemigrations' doesn't take in the latest model that was added to models.py.

Effectively, it is not taking the latest copy of models.py for the migrations, it is using the one that existed BEFORE the view was called.

Is there a way to use the latest (appended with the required model) models.py file for the migration commands?

#Here we are attempting to create a user's portfolio table as soon as his registration is complete
            
            #Step1: Adding schema to model.py
            
            modeladdscript = '\n\nclass '+ username + '(models.Model):'
            modeladdscript = modeladdscript + '''
stock_id = models.CharField(max_length = 20)
stock_name = models.CharField(max_length = 100)
qty = models.IntegerField(default = 0)
investment = models.FloatField()
hold = models.CharField(max_length = 50)'''
            
            #Step 2: Getting the location of models.py in fileloc

            fileloc ='portfolio\models.py' #Need to figure out how to get location of portfolio/models.py
            
            #Step 3: Opening models.py and appending the model add script

            with open(fileloc,"a") as f:
                f.write(modeladdscript)
            
            #Step 4: Closing models.py
            f.close()
            #Works absolutely fine till here

            # Make migrations
            call_command('makemigrations')  #This command is not taking the model that has been added above at the time of user creation.

            # Remove all the terminal colors, less parsing later.
            os.environ['DJANGO_COLORS'] = 'nocolor'

            # Capturing the list of applied and unapplied migrations 
            out = StringIO()
            call_command('showmigrations', stdout=out)

            # Clean up the line, and remove all applied migrations
            work = [line.strip() for line in out.getvalue().split('\n') if not line.startswith(' [X]')]
            # Keep looping until we run out of lines.
            while work:
                app_name = work.pop(0)
                while work and work[0].startswith('['):
                    migration_name = work.pop(0)[4:]
                    app_path = apps.get_app_config(app_name).module.__file__
                    # Print the whole path to the migration file that corresponds to this migration
                    print('--', os.path.abspath(os.path.join(app_path, '../migrations/', '{}.py'.format(migration_name))))
                    call_command('sqlmigrate', app_name, migration_name[:8])
            
            # Applying all pending migrations
            call_command('migrate')
over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda