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. # limitations under the License.
from copy import deepcopy, copy from copy import deepcopy, copy
from datetime import date, datetime from datetime import date, datetime, timedelta
import logging import logging
import six import six
from uuid import UUID as _UUID from uuid import UUID as _UUID
@@ -429,11 +429,27 @@ class DateTime(Column):
""" """
db_type = 'timestamp' 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): def to_python(self, value):
if value is None: if value is None:
return return
if isinstance(value, datetime): if isinstance(value, datetime):
return value 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): elif isinstance(value, date):
return datetime(*(value.timetuple()[:6])) return datetime(*(value.timetuple()[:6]))

View File

@@ -492,12 +492,7 @@ class BaseModel(object):
if keys != other_keys: if keys != other_keys:
return False return False
# check that all of the attributes match return all(getattr(self, key, None) == getattr(other, key, None) for key in other_keys)
for key in other_keys:
if getattr(self, key, None) != getattr(other, key, None):
return False
return True
def __ne__(self, other): def __ne__(self, other):
return not self.__eq__(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) .. autoclass:: DateTime(**kwargs)
.. autoattribute:: truncate_microseconds
.. autoclass:: Decimal(**kwargs) .. autoclass:: Decimal(**kwargs)
.. autoclass:: Double(**kwargs) .. autoclass:: Double(**kwargs)