Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
Editando el archivo models.py y migrando los cambios a la base de datos en el mismo código python

Estoy buscando editar un archivo models.py para una aplicación y luego migrar los cambios a la base de datos (postgreSQL) en el mismo código de Python.

En la definición de vista que se supone que debe realizar esto, estoy haciendo lo siguiente:

  1. Abrir models.py
  2. Agregar el modelo de la nueva tabla a los modelos existentes
  3. Cerrar models.py
  4. Ejecutar makemigrations
  5. Ejecutar sqlmigrate
  6. Ejecutar migrar

Funciona bien hasta el paso n.º 3. El modelo de la nueva tabla se agrega a models.py, pero 'makemigrations' no incluye el último modelo que se agregó a models.py.

Efectivamente, no está tomando la última copia de models.py para las migraciones, está usando la que existía ANTES de llamar a la vista.

¿Hay alguna manera de usar el archivo models.py más reciente (adjunto con el modelo requerido) para los comandos de migración?

 #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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!