liveBook · Manning

Primary key

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

A primary key is a column or set of columns that uniquely identifies each record in a relational database table.

When data is split into separate tables to reduce repetition, each record needs a dependable identity. A primary key is a column whose value is unique across its table. Foreign keys use those identities to reconnect related records. section 10.3.2

Choose an identifier that will remain useful as the application changes:

  • An existing unique value, such as a social security number, can serve as the key. A separate ID column is often easier and more future-proof because it does not depend on the stored data remaining unique. section 10.3.2
  • An auto-incrementing integer provides a unique value as each new row is inserted. section 10.3.2
  • A UUID provides an identifier unique beyond one table, which can help when database structures and uses change. section 10.3.2

Load related records

In a CSV-to-database migration, create customers, addresses, and products first. Committing those records generates their primary-key values; the values are then available when creating orders and their associated items. section 10.7.1

class User(UserMixin, db.Model):                                          #1
    __tablename__ = "user"                                                #2
    user_uid = db.Column(db.String, primary_key=True, default=get_uuid)   #3
    first_name = db.Column(db.String, nullable=False)                     #4
    last_name = db.Column(db.String, nullable=False)                      #4
    email = db.Column(db.String, nullable=False,                          #4
    unique=True, index=True)                                            #4
    hashed_password = db.Column("password",                               #4
    db.String, nullable=False)                                          #4
    active = db.Column(db.Boolean, nullable=False, default=False)         #4
    created = db.Column(db.DateTime, nullable=False,                      #5
    default=datetime.utcnow)                                            #5
    updated = db.Column(db.DateTime, nullable=False,                      #5
    default=datetime.utcnow, onupdate=datetime.utcnow)                  #5
 
    def get_id(self):
        return self.user_uid
 
    @property
    def password(self):
        raise AttributeError("user password can’t be read")
 
    @password.setter
    def password(self, password):
        self.hashed_password = generate_password_hash(password)
 
    def verify_password(self, password):
        return check_password_hash(self.hashed_password, password)
 
    def __repr__(self):
        return f"""
        user_uid: {self.user_uid}
        name: {self.first_name} {self.last_name}
        email: {self.email}
        active: {'True' if self.active else 'False'}
        """

The User model marks user_uid as the primary key and supplies a UUID-generating default. Its email column is separately marked unique: uniqueness alone does not make that column the chosen primary key. section 8.2.1

The practical choice is not just whether a value is unique today. Pick a key that lets other records refer to it reliably as the data and application evolve. section 10.3.2

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Defines table-wide uniqueness, compares existing values with generated integers and UUIDs, and shows when loaded records receive keys.
Examples
Uses social security numbers, auto-incrementing integers, and a UUID-backed User model to illustrate identifier choices.
What it assumes
Assumes familiarity with Python model classes and CSV data while defining primary keys and relational links.
What you can do after
Apply it via SQLAlchemy by configuring a UUID-backed primary-key column and committing records before creating related orders.
How it connects
Links database normalization, foreign keys, SQLAlchemy models, and user authentication to record identifiers.

Also explained in

Compare how 21 books explain primary key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.