简体   繁体   English

如何使用 Django 查询集基于现有数据库的日期应用过滤器

[英]How to apply filter based on dates of an already existing database with Django Queryset

So i have the below's QuerySet output:所以我有下面的QuerySet output:

<QuerySet [{'price': 12.515, 'price_date': datetime.datetime(2017, 3, 13, 0, 0, tzinfo=)}, {'price': 12.335, 'price_date': datetime.datetime(2017, 3, 14, 0, 0, tzinfo=)}, {'price': 12.37, 'price_date': datetime.datetime(2017, 3, 15, 0, 0, tzinfo=)}, {'price': 12.35, 'price_date': datetime.datetime(2017, 3, 16, 0, 0, tzinfo=)}, {'price': 12.305, 'price_date': datetime.datetime(2017, 3, 17, 0, 0, tzinfo=)}... <QuerySet [{'price': 12.515, 'price_date': datetime.datetime(2017, 3, 13, 0, 0, tzinfo=)}, {'price': 12.335, 'price_date': datetime.datetime(2017, 3, 14, 0, 0, tzinfo=)}, {'price': 12.37, 'price_date': datetime.datetime(2017, 3, 15, 0, 0, tzinfo=)}, {'price': 12.35, 'price_date': datetime.datetime(2017, 3, 16, 0, 0, tzinfo=)}, {'price': 12.305, 'price_date': datetime.datetime(2017, 3, 17, 0, 0, tzinfo= )}...

How can i get say the price with price_date = 11-26-21 (November 26th 2021)?我怎么知道 price_date = 11-26-21(2021 年 11 月 26 日)的价格? Or if i want to filter by latest 30 prices?或者如果我想按最新的 30 个价格过滤?

Thanks谢谢

You can use either datetime objects or strings inside the filter expression:您可以在过滤器表达式中使用日期时间对象或字符串:

filter_date = datetime.now()
Product.objects.filter(price_date=filter_date)
Product.objects.filter(price_date__lte=filter_date)

# or
Product.objects.filter(price_date__lte="2021-11-27 20:00:00")
Product.objects.filter(price_date="2021-11-27")

For the last 30 items, you would order the query set according to the price_date reversed and then take the first 30 items.对于最后 30 个项目,您将根据 price_date 反转的查询集排序,然后取前 30 个项目。

If you already have an initial QuerySet , you can still filter your results.如果您已经有一个初始QuerySet ,您仍然可以filter您的结果。

To extract the price, use values_list要提取价格,请使用values_list

prices = qs.filter(price_date='2021-11-26').values_list('price', flat=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM