Keys in SQLAlchemy

Learn about keys and the keyword nullable in SQLAlchemy.

Primary key

Let’s look at the following code:

id = Column(types.Integer, primary_key=True)

The id field indicates that it is the primary key. This means that no two records can have the same id in this table. In other words, the primary key must remain unique at all times. When a record is submitted, it overwrites the existing record with the same id, if any. The exception is when the id is not specified in the added record. In that case, the database assigns the record a new, currently unused id. We can do this by not assigning it any value when we create it. An alternative is to set that value to None.

Get hands-on with 1200+ tech skills courses.