Opened 9 years ago
Closed 9 years ago
#25760 closed New feature (duplicate)
Implement DateTime to Date Expression/Transform
Reported by: | Josh Smeaton | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | expressions |
Cc: | josh.smeaton@… | Triage Stage: | Accepted |
Has patch: | yes | Needs documentation: | yes |
Needs tests: | yes | Patch needs improvement: | yes |
Easy pickings: | no | UI/UX: | no |
Description
There's a bunch of date part extracts/transforms implemented, but nothing to transform a datetime into a date. This is a really important function for aggregating by date (when you have a datetime).
The beginnings of such a transform would be:
class ToDate(Transform): function = 'DATE' # MySQL and SQLite output_field = DateField() def as_postgresql(self, compiler, connection): self.template = '(%(expression)s)::date' return super().as_sql(compiler, connection) def as_oracle(self, compiler, connection): self.function = 'TRUNC' return super().as_sql(compiler, connection)
And that would then be registered against the DateTimeField type with the lookup "date". Tests and documentation would also be required.
#25556 is moving the existing lookups.XTransform transforms to a new module under django.db.models.expressions.datetime. The above transform should be implemented in the same location.
The name of the Transform is also interesting. I'm not committed to the ToDate or even Date name, because that could imply it accepts types other than a DateTime. There should definitely be some parsing to ensure it's only going to accept a datetime (either at init or resolve time).
This ticket will be a really good introduction to working with the ORM for a relatively experienced django developer. It's not easy pickings/easy, but it's a fairly contained patch that won't touch a large surface area.
This was already implemented for Django 1.9 in #9596 ( 44f3ee77166bd5c0e8a4604f2d96015268dce100 ).