Search code examples
djangodjango-modelsdjango-viewsdjango-channelsdjango-signals

How to auto update data in django?


I am trying to build eCommerce application in Django. In each product I have three label tags which are is_new, is_hot, is_promo.

  1. is_new will be True when a product will create, I have done it. But the system needs to automatically make is_new to False when a product is older than 7 days. I have added created_date field in Product model. How could I auto update is_new to False? Any hints?

  2. is_hot will be True when a product will most sold. Actually the first two product will be hot. And when other product goes hot then previous hot products will be automatically False. How to do it? Hints?

  3. is_promo will be True when I will add discount to a product. And it will be False when I will remove the discount. Any hints?


Solution

  • How you implement these depends on how you're handling the related data.

    • is_new you need the creation date.
    • is_hot you need related sold count and a value to compare it too, like hot_threshold_count or something.
    • is_promo you probably want this linked to promotion details.

    Here's a rough sketch on how I would handle this:

    from django.utils import timezone
    from django.conf import settings
    
    
    class Product(models.Model):
        ...  # name, etc
        creation_datetime = models.Datetime(auto_add_now=True)
        sold_count = models.Integer(default=0)
    
        @property
        def is_hot(self) -> bool:
            return self.sold_count >= settings.HOT_COUNT_THRESHOLD
    
        @property
        def is_new(self) -> bool:
            elapsed_days = (timezone.now() - self.creation_datetime).days
            return elapsed_days <= settings.MAX_NEW_DAYS
    
        @property
        def is_promo(self) -> bool:
            has_promos = bool(Promotion.objects.filter(product=self).count())
            return has_promos
    
    
    
    class Promotion(models.Model):
        creation_datetime = models.Datetime(auto_add_now=True)
        product = models.ForeignKey(Product)
        discount_percentage = models.Float()
    
    
    

    WHERE: settings.MAX_NEW_DAYS is a timedelta object