Validating unique fields and foreign keys with SQLAlchemy
How do you handle unique fields in your APIs? I come from Django, where validations were done automatically.
Let's take a simple example: the email address must be unique for each user.
I've tried three approaches:
1- Manual - Before creating a record, run a query to search by email address, perform the search, and throw an exception if it already exists.
2- Automated - Use inspect to search all model fields for unique fields and foreign keys. Then, run a query for each of those fields, and if it finds a record, throw an exception. This also works for foreign keys.
3- Let it fail on insertion, and handle the exception thrown by SQLAlchemy.
If anyone has tried another method or has a better way to do this, I would appreciate it if you could share it.
Posted Jan 30, 2026, 5:19 AM UTC