I have a user class which looks like this:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(15), unique=True, nullable=False)
last_name = db.Column(db.String(15), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
def __repr__(self):
return f"User('{self.first_name}', '{self.last_name}', '{self.email}')"
As you can see, first_name
and last_name
have to be unique, but that's not really what I want. Instead, I'd like the full name to be unique, so first_name
and last_name
together has to be unique. How can I do that?
CodePudding user response:
You can use a Declarative Table Configuration and define a UNIQUE constraint. However, keep in mind that there can be several people with the same first and last name combination.
class User(db.Model, UserMixin):
__table_args__ = (db.UniqueConstraint('first_name', 'last_name'),)
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(15), nullable=False)
last_name = db.Column(db.String(15), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
def __repr__(self):
return f"User('{self.first_name}', '{self.last_name}', '{self.email}')"