在同一python代码中编辑models.py文件并将更改迁移到数据库
我希望为应用程序编辑models.py文件,然后用相同的python代码将更改迁移到数据库(postgreSQL) 在本应执行此操作的视图定义中,我执行以下操作:在同一python代码中编辑models.py文件并将更改迁移到数据库,python,python-3.x,django,postgresql,Python,Python 3.x,Django,Postgresql,我希望为应用程序编辑models.py文件,然后用相同的python代码将更改迁移到数据库(postgreSQL) 在本应执行此操作的视图定义中,我执行以下操作: openmodels.py 将新表的模型附加到现有模型 Close models.py 运行makemigrations 运行sqlmigrate 运行迁移 在步骤3之前,它工作正常。新表的模型正在添加到models.py,但“makemigrations”不接受添加到models.py的最新模型 实际上,它不是为迁移获取models
#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')