0

I have following Model in existing db:

class Advert(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime, nullable=False, default = datetime.utcnow)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable = False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    category = db.Column(db.String(50), nullable=False, unique=True)

I just want to remove unique=True from my Model. How to do that?

Jessi
  • 1,378
  • 6
  • 17
  • 37
cheng
  • 1
  • 3
  • Use the alter SQL statement directly to your database created after removing unique attribute in the code base. Another way is to use a library like Flask-migrate but not 100% sure whether Flask-migrate would catch those attribute changes. – Jessi Feb 18 '20 at 16:30
  • I do that through flask-migrate and remove this unique=true line in code but flask-migrate dont detected any changes in schema – cheng Feb 18 '20 at 16:35
  • Yea, then the only option you have is to run the alter SQL statement directly to your db. – Jessi Feb 18 '20 at 16:36
  • Then, how to do that directly in my db? Through command line? – cheng Feb 18 '20 at 16:40
  • Go inside your database and run a SQL command. – Jessi Feb 18 '20 at 16:41
  • if you are using MySQL then command should be something like mysql -u root -p – Jessi Feb 18 '20 at 16:44
  • I use sqlalchemy and sqlite – cheng Feb 18 '20 at 16:45
  • How do you access your database in general? Meaning where do you see the data in the database? That is the place that you need to run the SQL command. – Jessi Feb 18 '20 at 16:50
  • All the stuff with db i use in command prompt. In my shell i import db from my app, then models and do the things – cheng Feb 18 '20 at 16:58
  • I think you need to figure out how to access to your sqllite database, where you can make sql queries directly into the db that you've selected. – Jessi Feb 18 '20 at 17:08
  • Either above or you can create a python script that has something like below. sql_query = 'your_alter_sql_query' db.engine.execute(sql_query) and run the python script. – Jessi Feb 18 '20 at 17:09

1 Answers1

1

I would like to suggest using Alembic for the database migration.

Let say if you want to alter the table. Just create an empty scheme migration alembic revision -m "alter table"

then you can add the alter here:

from alembic import op
import sqlalchemy as sa

revision = 'xxx'
down_revision = 'xxx'

def upgrade():
    op.execute('ALTER TABLE xx ... ')
    # Add the ALTER query here

def downgrade():
    pass
    # Add the ALTER query here
Amzar
  • 80
  • 7