0

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?

codermrhasan
  • 15
  • 2
  • 5
  • you can write the logic in the views.py itself. As in query for all the products which are 7 days old and add the logic to your home_view. So that whenever the home page is rendered it will do all the preprocessing and give appropriate results. – manask322 Mar 29 '20 at 06:41
  • also, look into [@property](https://docs.djangoproject.com/en/3.0/topics/db/models/#model-methods) for the is_new, and is_promo attributes. – AMG Mar 29 '20 at 14:17
  • Hey same thing I have done. But it only work when i restart the server or save codebase. then it automatically updates the view. I think django has by default caching. I've tried generic view on home Listview. – codermrhasan Mar 30 '20 at 05:07

1 Answers1

0

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

monkut
  • 42,176
  • 24
  • 124
  • 155