1

Consider the following code:

class User(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    email=db.Column(db.String,unique=True)
    name=db.Column(db.String)
    password=db.Column(db.String)
    registration_num=db.Column(db.Integer,unique=True)

    def __repr__(self):
          return "<Name %r>, <id %r>" %(self.name,self.id)

Here I am trying to create a user with unique email id (later to be used as login id) and unique registration number (later to be used as folder name to save user submitted data). While email column rejects non unique values, registration_num does not raise any flag no matter how many users i create with same registration number.

Given below is the decorator used for registration page:

@app.route('/register', methods=['GET','POST'])
def register():
    if request.method == 'POST':
        userpass=request.form["password"]
        usermail=request.form["username"]
        nameofuser=request.form["name"]
        reg_num=int(request.form["r_num"])
        u=models.User(email=usermail,name=nameofuser,password=userpass,registration_num=reg_num)
        db.session.add(u)
        db.session.commit()
        return redirect(url_for('login'))

    return render_template('register_form.html')

What am i doing wrong here?

ipcamit
  • 330
  • 3
  • 16
  • possible duplicate of [How to model a \`UNIQUE\` constraint in SQLAlchemy?](http://stackoverflow.com/questions/14355499/how-to-model-a-unique-constraint-in-sqlalchemy) – Celeo Apr 29 '15 at 19:48

1 Answers1

3

I suppose you declared email as UNIQUE in the database, but not registration_num. Setting unique=True in the model does not automatically influence the database and SQLAlchemy does not check if there are some rows with that value already. unique=True it is used by create_all or sqlalchemy-migrate.

Bartosz Marcinkowski
  • 6,651
  • 4
  • 39
  • 69
  • HI. Whenever i edited any model i did migrate (as explained in mega flask tutorial website) but same problem remained. So taking que from your answer I deleted the old database and started fresh. Now it is working fine! I dont get it. If we migrate wouldnt it update tables accordingly? or unique has to be declared when we first create the data base? – ipcamit May 01 '15 at 06:21
  • It depends on what you use to migrate. The way I do it is: I create a migration script for sqlalchemy-migrate and I explicitly include "alter table" if I add "UNIQUE" to a column of a model. You could have a totally magic tool that compares the model with database tables and can guess what to do, but you obviously don't use it :) – Bartosz Marcinkowski May 01 '15 at 06:49