Defining Models with a Foreign Key
Begin by opening yourmodels.py file where your table schemas are defined. In the Post model, add a new column named owner_id to reference the user who owns the post. This column should have the same data type as the primary key in the users table (i.e., an integer). Additionally, set a foreign key constraint to reference the id column of the users table with a cascading delete option. This ensures that if a user is removed, all associated posts will be automatically deleted. Mark the field as non-nullable so that every post must have an owner.
Here is the final code implementation for the models:
How It Works
- The
owner_idcolumn in thepoststable is defined as anIntegerto mirror theidcolumn in theuserstable. - The parameter
ForeignKey("users.id", ondelete="CASCADE")creates the relationship between the tables. TheCASCADEoption ensures that if a user is deleted, all their associated posts are removed automatically. - By setting
nullable=False, you enforce that every post must be linked to an existing user.
Updating the Database Schema
When you restart your application, SQLAlchemy verifies if the table already exists. If theposts table is already present, the new column won’t be added automatically. In production environments, it is recommended to use a migration tool, such as Alembic, to update table schemas safely. However, during development, you can manually drop the posts table using PgAdmin or executing SQL, then restart the application to let SQLAlchemy create a new table based on the updated models.
Remember to always back up your data before performing manual database schema modifications.
Verifying the Changes in PostgreSQL
After restarting your application, ensure that the new schema is applied. Use your PostgreSQL query tool to run the following command:owner_id column defined as non-null. Additionally, if you inspect the column constraints, the foreign key will include the “on delete cascade” action.
────────────────────────────────────────────
Testing the Foreign Key Constraint
Before testing, verify that there are entries in theusers table:
owner_id (make sure it matches an existing user ID):
owner_id (e.g., using NULL or a non-existent user ID) will result in a database error due to the non-null constraint or a foreign key violation.
────────────────────────────────────────────
Testing the “On Delete Cascade” Functionality
To verify the cascading delete behavior, delete a user whose ID is referenced by one or more posts. For example, if a user with an ID of20 exists, execute:
posts table with the query below:
owner_id of 20 should have been automatically deleted because of the cascade rule.
Be cautious when using cascading deletes in production. Unintended deletions may occur if proper validations and backups are not in place.