[Answer]-How to get the same date result from Model.objects.create and Model.objects.get in Django?

1👍

Simply pass an datetime object to the create method:

from datetime import date
obj = SomeModel.objects.create(date=date(2015, 5, 18))

or

obj = SomeModel.objects.create(date=date.strftime('2015-05-18', '%y-%m-%d'))    

0👍

There are two ways Django transforms the data in a model. The first, when saving the model the data is transformed to the correct data type and send to the backend. The data on the model itself is not changed. The second, when the data is loaded from the database, it is converted to the datatype that Django thinks is most appropriate.

This is by design: Django does not want to do any magic on the models itself. Models are just python class instances with attributes, so you are free to do whatever you want. This includes using the string u'2015-05-18' as a date or the string 'False' to store as True (yeah that’s right).

The database cannot store dates as arbitrary data types, so in the database it is just the equivalent of a Python date object. The information that it used to be a string is lost, and when loading the data directly from the database with get(), the data is consistently converted to the most appropriate Python data type, a date.

👤knbk

Leave a comment