Opened 5 years ago

Closed 5 years ago

#16312 closed New feature (wontfix)

models.DateField() doesn't convert a datetime.datetime() to

Reported by: jedie Owned by: nobody
Component: Uncategorized Version: master
Severity: Normal Keywords: DateField
Cc: Triage Stage: Design decision needed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


IMHO models.DateField() should convert a given datetime.datetime() to It makes this in DateField.to_python(), but the model value is a datetime.datetime()


class Foo(models.Model):
   date = models.DateField()

a = Foo(, month=1, day=1)) # returns a, ok.
a = Foo(date=datetime.datetime(year=2001, month=1, day=1)) # Failure: returns a datetime.datetime() and not a date

Change History (4)

comment:1 Changed 5 years ago by Łukasz Rekucki

Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset
Triage Stage: UnreviewedAccepted

comment:2 Changed 5 years ago by anonymous

Triage Stage: AcceptedDesign decision needed
Type: BugNew feature

I sympathise with the reporter as the automatic conversion of values assigned to DateField and DateTimeField to the underlying type would certainly reduce the number of bugs in our codebase.

Unfortunately that's a more general issue, as all the fields bundled with Django don't perform any validation or conversion on assignment (look at BooleanField and IntegerField for a simple example). The validation and conversion is performed only on saving and loading data from database. Changing only the behavior of DateField and DateTimeField would introduce an inconsistency and changing the behavior of all fields would break a lot of code in the wild.

I'm setting this ticket to design decision needed as this is a nice feature proposal, but it introduces a major backwards incompatibility.

comment:3 Changed 5 years ago by Marek Stępniowski

↑ That was me

comment:4 Changed 5 years ago by Aymeric Augustin

Resolution: wontfix
Status: newclosed

Auto-"conversion" of values paves the way for silent data corruption, that isn't a good idea. (I actually think Django is a bit laxist in its to_python methods.) Strict type checking isn't good either — Python favors duck typing.

Since DateField has historically accepted datetimes (and DateTimeField accepted dates), there's not much we can do without breaking backwards compatibility.

zuber is right: an isolated change to DateField isn't the way to go. If you want to work on this, please send a sufficiently detailed proposal to django-developers, summarizing the general problem and addressing backwards compatibility.

Note: See TracTickets for help on using tickets.
Back to Top