这里我如何过滤从过去一个月到这一天添加的所有产品。
模型.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])
关于python - 如何在 Django 中过滤具有日期范围的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56993645/