Django + Supabase Backend Helper
Expert guidance for working with a Django REST API backend that integrates Supabase PostgreSQL with pgvector for vector similarity search and OpenAI embeddings.
What This Skill Does
Provides comprehensive context and best practices for developing, testing, and maintaining a Django backend with:
Supabase PostgreSQL database with pgvector extensionOpenAI embeddings for vector similarity searchDjango REST Framework API structureMulti-app Django architectureAuthentication migration planning (Supabase → Clerk)Instructions
When working with this Django + Supabase backend codebase:
1. Environment Setup
Before any code changes:
Verify virtual environment is activated (`venv/` directory)Check `.env` file contains required variables: `SECRET_KEY`, `DB_PASSWORD`, `DB_URL`, `DB_KEY`, `OPENAI_KEY`Ensure PostgreSQL connection to Supabase is configured in settings2. Database Operations
When modifying models or schema:
Always run `python manage.py makemigrations` after model changesReview generated migration files before applyingApply migrations with `python manage.py migrate`Remember the database uses pgvector extension for 1536-dimensional embeddingsFor vector similarity operations:
Use the Supabase RPC function `match_documents` for similarity searchDefault similarity threshold is 0.3, returns top 3 matchesActivityEmbedding model stores vectors with metadata3. Django Apps Structure
Understand the app boundaries:
**users/**: Profile management (note: currently has Supabase auth, migrating to Clerk)**activities/**: Activity, Event, and ActivityEmbedding models (STAR method structure)**applications/**: Application and QuestionList models**ai/**: AI-powered analysis, EventSuggestion, embedding generationWhen adding features:
Place code in the appropriate app based on domainKeep AI/OpenAI logic in the `ai/` appActivity data management belongs in `activities/`4. API Development
When creating or modifying endpoints:
Use Django REST Framework serializers and viewsetsEndpoints under `/api/ai/` handle AI-powered operationsAPI documentation auto-generates at `/swagger/` and `/redoc/`Note: `/api/activities/` endpoints are currently commented out in URLs5. AI Integration Guidelines
For OpenAI embedding operations:
Use `text-embedding-3-small` model for consistencyChunk text to max 8000 tokens using tiktokenStore embeddings in ActivityEmbedding model (1536 dimensions)Use `parse_ai_suggestion_to_json` helper to structure search resultsFor vector search:
Query through Supabase RPC `match_documents` functionResults include similarity scores and metadataFormat responses as ability lists with fit scores6. Testing
Before committing code:
Run `python manage.py test` for full test suiteRun `python manage.py test <app_name>` for specific app testsVerify migrations apply cleanlyTest API endpoints through `/swagger/` UI7. Authentication Considerations
Be aware of ongoing migration:
Current: Supabase auth integration (users.SupabaseUser model)Future: Clerk authenticationAvoid deep dependencies on Supabase auth schemaDesign new features to accommodate auth provider changes8. Local Development Workflow
Standard development flow:
1. Activate virtual environment
2. Run `python manage.py runserver`
3. Access admin at `http://localhost:8000/admin/`
4. Test APIs via Swagger at `http://localhost:8000/swagger/`
5. Check ReDoc documentation at `http://localhost:8000/redoc/`
9. Code Quality Standards
Maintain consistency:
Follow Django best practices and conventionsKeep business logic in models/services, not viewsUse serializers for data validationDocument complex AI/vector operationsKeep environment secrets in `.env`, never commit10. Key Implementation Patterns
Vector similarity workflow:
1. Generate embeddings via OpenAI API (text-embedding-3-small)
2. Store in ActivityEmbedding with metadata
3. Query using Supabase `match_documents` RPC
4. Parse results with `parse_ai_suggestion_to_json`
5. Return structured JSON with fit scores
STAR method structure:
Events support Situation, Task, Action, Result fieldsInclude contribution and event rolesLink events to activities for comprehensive contextExamples
Adding a New Model with Embeddings
When adding a model that needs vector search:
1. Create model in appropriate app with `models.JSONField()` for embedding
2. Add embedding generation in save method or signal
3. Create migration: `python manage.py makemigrations`
4. Apply: `python manage.py migrate`
5. Update vector search logic to include new model
Creating AI-Powered Endpoint
Structure for new AI endpoints:
1. Define serializer in `ai/serializers.py`
2. Create view in `ai/views.py` (use DRF viewsets)
3. Generate embeddings using OpenAI client
4. Query Supabase `match_documents` with embedding
5. Parse results with helper functions
6. Return structured response
Database Schema Changes
Safe migration workflow:
1. Modify model in appropriate `models.py`
2. Run `python manage.py makemigrations`
3. Review generated migration file
4. Test migration on local database
5. Run `python manage.py migrate`
6. Verify changes in admin panel or database
Important Notes
**Database**: Supabase PostgreSQL with pgvector extension is required**Authentication**: Currently using Supabase auth, migrating to Clerk**Vector Dimensions**: All embeddings are 1536 dimensions (OpenAI text-embedding-3-small)**Commented Code**: Some activity endpoints are commented in URLs configuration**Admin Access**: Superuser required for admin panel access**API Docs**: Always available at `/swagger/` and `/redoc/` for referenceConstraints
Must maintain PostgreSQL + pgvector compatibilityOpenAI API key required for embedding generationSupabase connection required for vector searchDjango REST Framework required for API structureEnvironment variables must be configured in `.env`Authentication system in transition (plan for Clerk integration)