How to Get Foreign Keys Horribly Wrong
10 months ago
- #PostgreSQL
- #Database Optimization
- #Django
- Foreign keys are constraints that span multiple relations, making them harder to enforce.
- Common pitfalls and optimizations related to foreign keys include handling migrations, locking, and indexing.
- Django's `unique_together` is deprecated; use `UniqueConstraint` instead.
- Foreign keys implicitly create indexes unless `db_index=False` is set.
- Partial indexes can significantly reduce index size by excluding null values.
- Concurrent index operations (`CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`) minimize locking in live systems.
- Use `select_for_update(of=('self',))` to avoid locking related tables unnecessarily.
- Set `no_key=True` in `select_for_update` to allow referencing objects to be created without blocking.
- Always check generated SQL in migrations to avoid unintended side effects.
- Order migration operations carefully to minimize downtime and ensure consistency.