3

Here how can i filter all products which are added from within the past one month to this date.

models.py

class Product(models.Model):
    name = models.CharField(max_length=250)
    description = models.TextField(blank=True)
    featured = models.BooleanField(default=False)
    added = model.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

views.py

def all_products(request):
    all_products = Product.objects.all()
    recently_added_products = Product.objects.filter(...)
    context = {'all_products':all_products,'recent_products':recent_products}
    return render(request,'products_list.html',context)

3 Answers 3

2

You can use the range filter to specify a date range (inclusive):

from django.utils import timezone

today = timezone.now().date()

Product.objects.filter(added__range=[today - timezone.timedelta(days=30), today])
Sign up to request clarification or add additional context in comments.

Comments

1

You can use python datetime and do something like this

import datetime

recently_added_products = Product.objects.filter(date__gte=datetime.date(2019, 7, 1), date__lte=datetime.date(2019, 7, 31))

Comments

1

We first need to calculate the previous month. We can for example use relativedelta [python-doc] from the python-dateutil package [PyPi]. We can thus install this package with:

pip install python-dateutil

Then we can filter the Products such that we get all Products that were added after or one prev_month with prev_month the datetime object that is exactly one month ago:

from dateutil.relativedelta import relativedelta
from django.utils.timezone import now

def all_products(request):
    all_products = Product.objects.all()
    prev_month = now() - relativedelta(months=1)
    recently_added_products = Product.objects.filter(added__gte=prev_month)
    context = {'all_products':all_products,'recent_products':recent_products}
    return render(request,'products_list.html',context)

We thus use the __gte lookup to filter all Products with an added date greater than one month ago.

Note: if you often filter, it might be better to add a db_index=True [Django-doc] on your added field:
class Product(models.Model):
    # ...
    added = model.DateTimeField(auto_now_add=True, db_index=True)

5 Comments

i got this from dateutil.relativedelta import relativedelta ModuleNotFoundError: No module named 'dateutil'
@Alicesmith: you need to install the package, with pip install python-dateutil for example
i implemented unknown_user solution but your solution also worked.Thank you .Is there any difference between these two solution.Which solution should i prefer more?
@Alicesmith: there are two small differences: unknown_user goes back 30 days in time, whereas this one a month (so for a month with 31/28/29 days) that is different. Furthermore if a Product is added in the future, unknown_user's solution will exclude that, whereas this one only looks for everythin added after this timestamp (so including "future" Products). Although since you use auto_add_now, that should (not) happen.
Okay i got this.Thank you so much for your time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.