简体   繁体   English

如何将列添加到现有表? 在 Flask SqlAlchemy

[英]How to add column to existing Table? in Flask SqlAlchemy

I have a flask SqlAclchemy table called User:我有一个名为 User 的 flask SqlAclchemy 表:

class User(db.Model):
    id = db.Column(db.INTEGER, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)

i have now edited it and added this line;我现在已经编辑它并添加了这一行; favCol = db.Column(db.String(12))

how do i update the table for it to recognize this new colum when i add a new user?当我添加新用户时,如何更新表格以使其识别这个新列? At the moment when i create a User like User(username="bob",favCol="red") it gives me an error:在我创建像User(username="bob",favCol="red")这样的用户时,它给了我一个错误:

TypeError: 'favCol' is an invalid keyword argument for User

I have heard of solution with Migrate although i would prefer re a simpler solution if possible我听说过 Migrate 的解决方案,但如果可能的话,我更喜欢更简单的解决方案

If you don't care about the data in the database getting erased.如果您不关心数据库中的数据被删除。 You can do the following:您可以执行以下操作:

from terminal if 'py' doesn't start python, try 'python'.如果“py”没有启动 python,则从终端尝试“python”。 press enter after each of these commands在每个命令后按 enter

py
from projectdirectory import db
db.drop_all()
db.create_all()

If you care about your existing data, you need to use something like flask_migrate which uses alembic in order to help you do database migrations while maintaining your data.如果您关心现有数据,则需要使用类似 flask_migrate 的东西,它使用 alembic 来帮助您在维护数据的同时进行数据库迁移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM