Merge pull request #526 from datastax/273

PYTHON-273 - option to make models with datetime comparable
This commit is contained in:
Adam Holmberg
2016-03-24 08:47:36 -05:00
3 changed files with 21 additions and 8 deletions

View File

@@ -13,7 +13,7 @@
# limitations under the License.
from copy import deepcopy, copy
from datetime import date, datetime
from datetime import date, datetime, timedelta
import logging
import six
from uuid import UUID as _UUID
@@ -429,10 +429,26 @@ class DateTime(Column):
"""
db_type = 'timestamp'
truncate_microseconds = False
"""
Set this ``True`` to have model instances truncate the date, quantizing it in the same way it will be in the database.
This allows equality comparison between assigned values and values read back from the database::
DateTime.truncate_microseconds = True
assert Model.create(id=0, d=datetime.utcnow()) == Model.objects(id=0).first()
Defaults to ``False`` to preserve legacy behavior. May change in the future.
"""
def to_python(self, value):
if value is None:
return
if isinstance(value, datetime):
if DateTime.truncate_microseconds:
us = value.microsecond
truncated_us = us // 1000 * 1000
return value - timedelta(microseconds=us - truncated_us)
else:
return value
elif isinstance(value, date):
return datetime(*(value.timetuple()[:6]))

View File

@@ -492,12 +492,7 @@ class BaseModel(object):
if keys != other_keys:
return False
# check that all of the attributes match
for key in other_keys:
if getattr(self, key, None) != getattr(other, key, None):
return False
return True
return all(getattr(self, key, None) == getattr(other, key, None) for key in other_keys)
def __ne__(self, other):
return not self.__eq__(other)

View File

@@ -54,6 +54,8 @@ Columns of all types are initialized by passing :class:`.Column` attributes to t
.. autoclass:: DateTime(**kwargs)
.. autoattribute:: truncate_microseconds
.. autoclass:: Decimal(**kwargs)
.. autoclass:: Double(**kwargs)