Skip to main content
 首页 » 编程设计

python之如何在 Django 中过滤具有日期范围的查询

2024年08月13日33zlslch

这里我如何过滤从过去一个月到这一天添加的所有产品。

模型.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 

View .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) 

请您参考如下方法:

您可以使用 range 过滤器指定日期范围(包括):

from django.utils import timezone 
 
today = timezone.now().date() 
 
Product.objects.filter(added__range=[today - timezone.timedelta(days=30), today])