Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter queries with date range in django

Tags:

python

django

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)

2 Answers

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])
like image 136
heemayl Avatar answered Dec 17 '25 06:12

heemayl


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))
like image 41
copser Avatar answered Dec 17 '25 08:12

copser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!