Do you know the difference between a static default and a dynamic callable in your ORM? It’s a small distinction in code that makes a massive difference in your database. 🚀 📍 Static Defaults These are defined once when the model is initialized. Every new record gets the exact same value. Use case: Setting a starting status (e.g., status='draft') or a counter starting at 0. 📍 Dynamic Defaults (Callables) These are calculated at the moment the record is created. By passing a function (like a lambda or a method), the ORM executes that logic for every single insert. Use case: Timestamps (datetime.now), UUIDs, or record-specific tokens. ⚠️ The Common Trap: One of the most frequent bugs is passing default=datetime.now() (with parentheses) instead of default=datetime.now. With (): The time is captured when the server starts. Every record will have the same timestamp until you restart the service! Without (): The ORM calls the function fresh for every new entry. Check out the infographic below for a side-by-side comparison using SQLAlchemy examples! #Python #ORM #SQLAlchemy #BackendDevelopment #CleanCode #SoftwareEngineering #Python #ORM #SQLAlchemy #Odoo #OdooDevelopment #BackendDevelopment #CleanCode #SoftwareEngineering #DatabaseDesign #ProgrammingTips #WebDevelopment #BackendEngineering #PythonDev #CodingBestPractices #ERP #FullStackDeveloper
Static vs Dynamic Defaults in ORM: SQLAlchemy Examples
More Relevant Posts
-
Your ORM is LIES and your database DIES…… Prisma. Sequelize. Type ORM [Object-Relational Mapping]. Great DX. Terrible SQL. Here's why 👇 You write this: await db.user.findMany({ include: { posts: true } }) Clean, right? Under the hood, your ORM fires: → 1 query to fetch all users → 1 query per user to fetch their posts 50 users = 51 queries. 500 users = 501 queries. This is the N+1 problem and ORMs generate it silently, constantly. More ORM traps that wreck performance: → Lazy loading pulling entire relations you never use → No query batching by default → Generated SQL with unnecessary subqueries and redundant joins → Zero awareness of your index structure The scary part? Your ORM abstracts the SQL, so you never see the damage. Most devs only find this during a production incident. By then, the query has run millions of times. Raw SQL isn't always the answer. But understanding what your ORM actually generates,https://lnkd.in/dYGfeSmt is non-negotiable. Dharmops shows you the real query behind your code and tells you exactly what's wrong. No guessing. No log diving at midnight. → Diagnose your queries free="https://lnkd.in/dYGfeSmt" Are you using an ORM in prod? Which one? 👇 #ORM #Prisma #DatabaseOptimization #BackendDevelopment #NodeJS #QueryPerformance #Dharmops #SoftwareEngineering #DevTools #TechFounders
To view or add a comment, sign in
-
-
Most data analysts on my team spent more time writing SQL than actually analysing data. So I built a fix — without touching our existing Superset setup. It's called a Text-to-SQL Sidecar: a standalone FastAPI microservice that sits alongside Apache Superset and turns plain English into validated, safe SQL. You ask: "which products had the highest return rate last quarter?" It generates, validates, and executes the SQL — then hands the results back. A few things I was deliberate about: → AST-level SQL validation (not string matching — trivially bypassable) → Per-database table allowlists so the LLM can only touch what it's supposed to → Schema caching so we're not hammering the DB on every request → LLM-agnostic design — swap the endpoint URL, change the model → Reasoning traces returned alongside SQL so analysts can actually trust the output Superset never needs to know it exists. It just receives SQL. I wrote up the full implementation — architecture, code walkthrough, and the design decisions that make it production-ready. Link in the comments 👇 #DataEngineering #AI #SQL #FastAPI #ApacheSuperset #LLM #Python
To view or add a comment, sign in
-
⚡Hey .NET Friends – PostgreSQL Just Joined the FunkyORM Party... After a few decades of wrestling .NET data-access layers (and watching frameworks come and go), we at Funcular Labs still believe the best tool is the one you barely notice... the one that just works. That's why we're genuinely excited to announce full PostgreSQL support in Funcular.Data.Orm—better known around here as FunkyORM—now live in version 3.1.0. You already know the drill if you've used our ORM with SQL Server: zero-configuration POCO mapping, lambda-powered LINQ queries that generate clean parameterized SQL, remote properties that flatten your object graphs without the N+1 tax, and performance that often leaves heavier ORMs in the dust. No DbContext boilerplate. No XML mapping files. Just your plain classes and the queries you’d write anyway. Now the same delightful API works seamlessly with Postgres. Our new PostgreSqlOrmDataProvider (built on Npgsql) handles all the dialect differences transparently—double-quoted identifiers for reserved words, LIMIT/OFFSET paging, RETURNING clauses on inserts, native BOOLEAN columns... everything you’d expect. You can literally swap providers and keep your entity classes untouched (yes, even the ones with [RemoteProperty] and [RemoteKey] magic). Whether you’re starting fresh or migrating an existing FunkyORM project, the experience is identical. And because we’re still the same lightweight micro-ORM at heart, you get the speed you love without giving up type safety or developer happiness. Want to give it a spin? Head over to the NuGet package and pull in the latest bits: https://lnkd.in/gMfmJWhc We’d love for you to try it out on your next (or current) Postgres project. Drop the provider in, point it at your database, run a few queries... then swing by the comments and tell us how it feels. Did it save you time? Make your code cleaner? Surprise you in a good way? We read every note. Here’s to simpler, faster data access—no matter which database you call home. #dotnet #csharp #postgresql #orm #microorm #FuncularLabs
To view or add a comment, sign in
-
From APIs to Databases — My FastAPI Learning Journey As I continue my journey of mastering FastAPI, I’ve reached an exciting milestone: connecting my API to a database and working with real data using SQL queries. Until now, building endpoints and handling requests felt powerful — but integrating a database takes things to a whole new level. It transforms APIs from static responses into dynamic, data-driven systems. 🔍 What I’ve learned so far: - Connecting Python applications to a relational database - Writing SQL queries to retrieve and create posts - Structuring backend logic for clean and scalable APIs - Understanding how data flows between client → API → database 💡 One thing that stood out: «Writing SQL inside a FastAPI project gives you full control over your data — something every backend developer must master.» Here’s a simple example of how I’m retrieving and creating posts: from fastapi import FastAPI, Depends import psycopg2 app = FastAPI() conn = psycopg2.connect( host="localhost", database="fastapi_db", user="postgres", password="password" ) cursor = conn.cursor() @app.get("/posts") def get_posts(): cursor.execute("SELECT * FROM posts;") posts = cursor.fetchall() return {"data": posts} @app.post("/createpost") def create_post(title: str, content: str): cursor.execute( "INSERT INTO posts (title, content) VALUES (%s, %s) RETURNING *;", (title, content) ) new_post = cursor.fetchone() conn.commit() return {"data": new_post} ⚙️ This is just the beginning — next, I’m aiming to explore: - ORM tools like SQLAlchemy / SQLModel - Database migrations - Optimizing queries and performance Consistency and depth are key. Instead of jumping between technologies, I’m focusing on going deep into backend development with FastAPI. #FastAPI #BackendDevelopment #Python #SQL #APIs #LearningJourney #SoftwareDevelopment
To view or add a comment, sign in
-
#PythonJourney | Day 147 — SQLAlchemy Models & API Endpoints Implementation Today was all about connecting the database layer with the API. This is where FastAPI meets SQLAlchemy and everything starts working together. Key accomplishments: ✅ Created comprehensive SQLAlchemy models: • User model (authentication & API keys) • URL model (main shortening logic) • Click model (event tracking) • ClickAggregate model (analytics summaries) • AuditLog model (compliance & debugging) ✅ Fixed PostgreSQL-specific imports: • JSONB type for flexible data storage • Proper index configuration • Relationship definitions with cascading deletes ✅ Implemented 8 API endpoints: • POST /api/v1/urls (create shortened URL) • GET /{short_code} (redirect to original) • GET /api/v1/urls (list user's URLs) • GET /api/v1/urls/{url_id} (get URL details) • GET /api/v1/urls/{url_id}/analytics (get analytics) • DELETE /api/v1/urls/{url_id} (delete URL) • GET /health (health check) ✅ Integrated database operations: • User authentication via API key • Permission checks (users can only see their own URLs) • Click tracking with geolocation & device detection • Soft deletes for data integrity • Audit logging for compliance ✅ Created test user creation script What I learned: → SQLAlchemy relationships make database operations elegant → Proper indexing strategy is crucial for performance → Cascade deletes prevent orphaned data → API key authentication is simpler than JWT for this use case → JSONB allows storing flexible analytics data in PostgreSQL The API is now fully functional with a real database. Next: write comprehensive tests and handle edge cases. #Python #FastAPI #SQLAlchemy #PostgreSQL #Backend #API #DatabaseDesign #SoftwareDevelopment
To view or add a comment, sign in
-
-
NOBOT - Status Update: Docker, ORM, and DB Design 🚀 Building in public means showing the process, even when it’s not "pixel-perfect". Here’s what’s happening with NOBOT: 1. Why PostgreSQL? 🐘 After a long brainstorming session (SQLite vs. one central hub), I decided to bet on PostgreSQL. With all the relations I have planned, Postgres just felt like the right, solid choice for the backbone of the system. 2. The Docker Dopamine Hit 🐳 There’s nothing like the satisfaction of seeing docker-compose up working for the first time. I just pushed the Dockerfile and docker-compose.yml to GitHub. Seeing the DB and data services running in containers gave me a huge smile – a small win for the infrastructure! 3. From Pydantic Contracts to ORM 🧹 I’m using Contract-Driven Development, so I started with Pydantic models to define how data should flow. Now I’m bridging that with an ORM. It lets me map my contracts directly to the database, keeps the code clean, and saves me from writing manual SQL modules. 4. Thinking Out Loud 🧠 The attached diagram is my current "brain dump." It’s changing every hour as I review my early contracts and refine the logic. Visualizing the schema helps me find edge cases before they turn into annoying bugs. I’m curious — what are your favorite tools for database design? I’m using dbdiagram.io right now, but sometimes I still think about the chaotic energy of Microsoft Paint! 😂 #BuildInPublic #Python #PostgreSQL #Docker #AI #RPA #SoftwareEngineering #NOBOT #IDP
To view or add a comment, sign in
-
-
✅ .NET Core Tips #10 — ORM (What it really is & why it matters) Most developers start by writing raw SQL. Then they discover ORM — and everything changes. 🔍 What is ORM? ORM (Object-Relational Mapper) lets you interact with your database using C# objects instead of raw SQL queries. You stop thinking in tables and start thinking in models. 🔧 Without ORM You write queries manually, handle parameters, execute commands, and map results yourself. It gives control — but leads to verbose code, more bugs, and harder maintenance. ✅ With ORM (EF Core) var student = await _context.Students .FirstOrDefaultAsync(s => s.Id == studentId); Cleaner, readable, and type-safe. Less boilerplate, fewer mistakes. Same result — better developer experience. 🚀 Why ORM is powerful: • No scattered SQL strings in your codebase • Strongly-typed queries with compile-time safety • Automatic relationship handling • Code-first migrations — schema lives in your code • Easier database switching (SQL Server → PostgreSQL) • No need to rewrite your full data access layer when changing DB 💡 Real-world tip ORM works best for everyday CRUD operations. For complex or performance-critical queries — use Stored Procedures alongside it. EF Core + Stored Procedures is a practical balance in production systems. ⚡ Performance tip — Use Projection Even with ORM, avoid over-fetching data. Use Select() to fetch only what you need: var students = _context.Students .Select(s => new { s.FullName, s.Email }) .ToList(); This reduces SQL payload, improves performance, and keeps queries efficient. 🧰 Popular .NET ORMs: • EF Core — standard choice for most applications • Dapper — lightweight and fast, stays close to SQL • NHibernate — mature and enterprise-focused 📌 Final thought ORM doesn't replace SQL. It builds on top of it. Combine ORM + SQL knowledge + Projection techniques — and you'll write scalable, maintainable, high-performance applications. #dotnet #csharp #efcore #orm #aspnetcore #backend #softwaredevelopment #performance
To view or add a comment, sign in
-
🐛 #PythonJourney | Day 148 — Debugging SQLAlchemy Models & Type Compatibility Today was about learning through debugging. I encountered multiple SQLAlchemy type compatibility issues and learned valuable lessons about database design. Key accomplishments: ✅ Fixed critical SQLAlchemy issues: • JSONB and INET are PostgreSQL-specific types • Must import from sqlalchemy.dialects.postgresql • Resolved naming conflicts (metadata is reserved) ✅ Solved type mismatches: • User.id must be UUID(as_uuid=True) • URL.user_id must match User.id type exactly • Foreign key constraints require compatible types • PostgreSQL is strict about type casting ✅ Debugged relationship definitions: • back_populates must reference correct class names • Cascade deletes prevent orphaned data • Bidirectional relationships need proper naming ✅ Created test user script: • Generates database tables automatically • Creates sample user with API key • Tests database connectivity ✅ All 5 SQLAlchemy models are now production-ready: • User (authentication) • URL (shortened URLs) • Click (event tracking) • ClickAggregate (analytics summaries) • AuditLog (compliance) What I learned today: → Database type safety is critical → PostgreSQL has its own type system (JSONB, UUID, INET) → SQLAlchemy type imports matter - core vs dialect-specific → Debugging error messages contain the actual problem - read them carefully → Foreign key constraints are strict about type compatibility The lesson: Sometimes the best learning comes from fixing errors. Each error message was an opportunity to understand the framework better. #Python #SQLAlchemy #PostgreSQL #DatabaseDesign #Backend #Debugging #SoftwareDevelopment #TechLearning
To view or add a comment, sign in
-
-
Your ORM is lying to you about performance. Every abstraction layer adds cost. Sequelize and TypeORM generate queries you never wrote and often never inspected. When your API slows down, the ORM is usually the first suspect - but most developers never look past it. Switch to pg and run raw SQL. Then use EXPLAIN ANALYZE directly from Node.js to see exactly what Postgres is doing. Here is a quick example: const { rows } = await pool.query(` EXPLAIN ANALYZE SELECT u.id, u.name, COUNT(o.id) AS order_count FROM users u JOIN orders o ON o.user_id = u.id GROUP BY u.id `); rows.forEach(row => console.log(row['QUERY PLAN'])); This gives you real execution time, seq scans, index hits - everything your ORM hides from you. Practical takeaway - run EXPLAIN ANALYZE on your five most-called endpoints this week. You will likely find at least one full table scan that a single index can eliminate. Have you ever caught a serious performance issue that your ORM was silently causing? #NodeJS #PostgreSQL #WebDevelopment #BackendEngineering #DatabasePerformance #SQLOptimization
To view or add a comment, sign in
More from this author
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development