Django Case and When for Seasonal Discounts

Title: Case & When — Conditional Discounts on Seasonal Flowers 🚀 Opening Hook: Imagine walking through a vibrant garden, each flower in full bloom, ready to make someone’s day. 🌺 A florist wants to offer seasonal discounts on bouquets, but managing these conditions is quite a task! Let's dive into how we can make this easier in Django! The Problem: Handling conditional discounts can be a mess if done naively. Here’s what NOT to do: ```python # BAD way to apply discounts def apply\_discount\(bouquet\): if bouquet.season == 'Spring': bouquet.price = 0.9 elif bouquet.season == 'Summer': bouquet.price = 0.85 elif bouquet.season == 'Fall': bouquet.price = 0.8 ``` The Solution: Introducing Django's `Case` and `When` for cleaner, more efficient discount logic. ```python # GOOD way using Case and When from django.db.models import Case, When, DecimalField, F Bouquet.objects.update\( price=Case\( When\(season='Spring', then=F\('price'\) 0.9\), When\(season='Summer', then=F\('price'\) 0.85\), When\(season='Fall', then=F\('price'\) 0.8\), default=F\('price'\), output\_field=DecimalField\(\) \) \) ``` Think of it as arranging a bouquet - each condition a unique flower, making the perfect ensemble! Did You Know? 💡 `Case` and `When` translate into efficient SQL, reducing the number of queries and enhancing performance. Why Use It? - ⚡ Performance impact: Fewer database hits mean faster apps! - 🧹 Code quality improvement: Cleaner, more readable logic. - 📈 Scalability advantage: Ready to handle growth during busy seasons! The Golden Rule: Keep your code blooming elegantly like a well-tended garden. Engagement Question: Have you used `Case` and `When` in your projects? Share your experience or a tip you've learned! 👇 Hashtags: #Django #Python #WebDevelopment #Backend #Performance #FlowerShop #DjangoORM

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories