Django:在日期以字符串形式存储时查询日期范围

huangapple go评论53阅读模式
英文:

Django : Query for date range when date is stored as string

问题

由于某些原因,我需要将日期存储为字符串“2023-03-03”,并且我需要使用日期范围来过滤这些数据。

给定起始日期(比如“2023-03-01”)和结束日期(“2023-03-04”),我需要找到给定日期之间的所有行。

目前,我正在使用以下查询:

Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"])

这个查询会返回结果。

我不太明白它是如何工作的。我想知道我正在使用的方法是否正确,或者是否有更好的方法来查询这些数据。

英文:

For some reasons I'm required to store date as string 2023-03-03 and I have a requirement to filter this data using date range.

Given starting date (say 2023-03-01) and end date (2023-03-04) I have to find all the rows between the given dates.

Currently I'm using this query

Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"])

which is giving results.

I'm not able to understand how it is working. I'm looking to see if this approach I'm following is right of if there's better approach to query this data.

答案1

得分: 1

这是 ISO 8601 日期格式的一个优点的结果(您正在正确使用):

当您按字母顺序对日期进行排序时,日期将按正确顺序排列。

Django/PostgreSQL 的 __range 查询也可以进行字母顺序比较,因此这是有效的。

因此,当您必须使用文本字段来存储日期时,只要在 ISO 8601 格式中输入它们,并根据需要进行比较/排序,只要在列上创建一个索引(db_index=True)。这不会像正常的 PostgreSQL 日期那样高效,并且日期特定的 PostgreSQL 功能需要转换,因此会更慢。

英文:

This is the result of one of the advantages of the ISO 8601 date format (which you are correctly using):

When you sort the dates alphabetically, the dates will be correctly ordered.

The django / postgres __range query can also compare alphabetically, so this works.

So when you have to use a text field for dates, you can totally put them into it in ISO 8601 format, and compare / order them as you wish, as long as you create an index on the column (db_index=True). It won’t be as efficient as normal postgres dates, and also date-specific postgres features need converting, so will be slower.

huangapple
  • 本文由 发表于 2023年3月9日 13:19:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75680696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定