7

I am using sqlite database and I declare the model as this:

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    login = db.Column(db.String(80), unique=True)
    password = db.Column(db.String(64))

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return self.id

    # Required for administrative interface
    def __unicode__(self):
        return self.username

And I have add a Model instance like this:

admin = admin.Admin(app, 'Example: Auth', index_view=MyAdminIndexView(), base_template='my_master.html')

admin.add_view(MyModelView(User, db.session))

db.drop_all()
db.create_all()

if db.session.query(User).filter_by(login='passport').count() <= 1:
    user = User(login = 'passport', password = 'password')
    db.session.add(user)
    db.session.commit()

However, if I comment the db.drop_all(), it will occur an error which is:

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: users.login [SQL: 'INSERT INTO users (login, password) VALUES (?, ?)'] [parameters: ('passport', 'password')]

And if do not comment the db.drop_all(), everything is fun. Because there are other tables on this database, I do not want to drop all the tables when I run it. Are there any other solutions to fix that?

Thanks a lot.

3 Answers 3

5

You're comparing the count to <= 1. So you'll attempt to create the new user even though it already exists. So it should probably simply be < 1:

if db.session.query(User).filter_by(login='passport').count() < 1:
    user = User(login = 'passport', password = 'password')
    db.session.add(user)
    db.session.commit()
Sign up to request clarification or add additional context in comments.

Comments

0

You can just run query, let's say:

db.session.query(User).delete()
db.session.commit()

OR

User.query.delete()
db.session.commit()

in that case, you will just remove everything from User table.

Comments

0

I was running into the same error.

if db.session.query(User).filter_by(login='passport').count() <= 1:
db.drop_all()
db.create_all()
user = User(login = 'passport', password = 'password')
db.session.add(user)
db.session.commit()

1 Comment

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.