Created
September 10, 2021 18:53
-
-
Save waylan/ee85c5517c5f27c05de9409a2c65984e to your computer and use it in GitHub Desktop.
A MonthField for the peewee ORM. Inspired by https://github.com/clearspark/django-monthfield.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from peewee import _BaseFormattedField, format_date_time, _date_part | |
import datetime | |
class MonthField(_BaseFormattedField): | |
field_type = 'DATE' | |
formats = [ | |
'%Y-%m', | |
'%Y-%m-%d', | |
'%Y-%m-%d %H:%M:%S', | |
'%Y-%m-%d %H:%M:%S.%f', | |
] | |
def db_value(self, value): | |
" Store datetime.date object of first day in db. " | |
month = self.python_value(value) | |
if month is not None: | |
return month.first_day() | |
return None | |
def python_value(self, value): | |
" Return Month object for given value. " | |
if value and isinstance(value, Month): | |
return value | |
elif value and isinstance(value, str): | |
return format_date_time(value, self.formats, Month.from_date) | |
elif value and isinstance(value, (datetime.datetime, datetime.date)): | |
return Month.from_date(value) | |
return None | |
def to_timestamp(self): | |
return self.model._meta.database.to_timestamp(self) | |
def truncate(self, part): | |
return self.model._meta.database.truncate_date(part, self) | |
year = property(_date_part('year')) | |
month = property(_date_part('month')) | |
""" | |
Month borrowed from https://github.com/clearspark/django-monthfield/ with modification. | |
Copyright (c) 2019, clearSpark | |
All rights reserved. | |
Redistribution and use in source and binary forms, with or without | |
modification, are permitted provided that the following conditions are met: | |
* Redistributions of source code must retain the above copyright notice, this | |
list of conditions and the following disclaimer. | |
* Redistributions in binary form must reproduce the above copyright notice, | |
this list of conditions and the following disclaimer in the documentation | |
and/or other materials provided with the distribution. | |
* Neither the name of django-monthfield nor the names of its | |
contributors may be used to endorse or promote products derived from | |
this software without specific prior written permission. | |
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | |
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | |
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | |
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
""" | |
def days(days): | |
return datetime.timedelta(days=days) | |
class Month(): | |
def __init__(self, year, month): | |
self.year = year | |
self.month = month | |
self._date = datetime.date(year=self.year, month=self.month, day=1) | |
@classmethod | |
def from_int(cls, months): | |
y, m = divmod(months, 12) | |
m += 1 | |
return cls(y, m) | |
@classmethod | |
def from_date(cls, date): | |
return cls(date.year, date.month) | |
@classmethod | |
def from_string(cls, date): | |
y = int(date[:4]) | |
m = int(date[5:7]) | |
return cls(y, m) | |
def __add__(self, x): | |
'''x is an integer''' | |
return Month.from_int(int(self) + x) | |
def __sub__(self, x): | |
'''x is integer or Month instance''' | |
if isinstance(x, Month): | |
return int(self) - int(x) | |
else: | |
return Month.from_int(int(self) - int(x)) | |
def next_month(self): | |
return self + 1 | |
def prev_month(self): | |
return self - 1 | |
def first_day(self): | |
return self._date | |
def last_day(self): | |
return self.next_month().first_day() - days(1) | |
def __int__(self): | |
return self.year * 12 + self.month - 1 | |
def __contains__(self, date): | |
return self == date | |
def __eq__(self, x): | |
if isinstance(x, Month): | |
return x.month == self.month and x.year == self.year | |
if isinstance(x, datetime.date): | |
return self.year == x.year and self.month == x.month | |
if isinstance(x, int): | |
return x == int(self) | |
if isinstance(x, str): | |
return str(self) == x[:7] | |
def __gt__(self, x): | |
if isinstance(x, Month): | |
if self.year != x.year: return self.year > x.year | |
return self.month > x.month | |
if isinstance(x, datetime.date): | |
return self.first_day() > x | |
if isinstance(x, int): | |
return int(self) > x | |
if isinstance(x, str): | |
return str(self) > x[:7] | |
def __ne__(self, x): | |
return not self == x | |
def __le__(self, x): | |
return not self > x | |
def __ge__(self, x): | |
return (self > x) or (self == x) | |
def __lt__(self, x): | |
return not self >= x | |
def __str__(self): | |
return '%s-%02d' %(self.year, self.month) | |
def __repr__(self): | |
return self.__str__() | |
def __hash__(self): | |
return hash(self.datestring()) | |
def datestring(self): | |
return self.first_day().isoformat() | |
isoformat = datestring | |
def range(self, x): | |
'''x must be an instance of Month that is larger than self. | |
returns a list of Month objects that make up the timespan from self to x (inclusive)''' | |
months_as_ints = range(int(self), int(x) + 1) | |
return [ Month.from_int(i) for i in months_as_ints ] | |
def strftime(self, fmt): | |
return self._date.strftime(fmt) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unittest | |
import peewee | |
import datetime | |
from peewee_monthfield import MonthField, Month | |
db = peewee.SqliteDatabase(':memory:') | |
class TestModel(peewee.Model): | |
month = MonthField() | |
class Meta: | |
database = db | |
class TestMonthField(unittest.TestCase): | |
database = db | |
requires = [TestModel] | |
def setUp(self): | |
if not self.database.is_closed(): | |
self.database.close() | |
self.database.connect() | |
self.database.create_tables(self.requires) | |
def tearDown(self): | |
if not self.database.is_closed(): | |
self.database.rollback() | |
try: | |
self.database.drop_tables(self.requires, safe=True) | |
finally: | |
self.database.close() | |
def test_model(self): | |
TestModel.create(month='2021-09') | |
TestModel.create(month=datetime.date(2021, 10, 1)) | |
TestModel.create(month=Month(2021, 11)) | |
s = TestModel.get(TestModel.month == datetime.date(2021, 9, 1)) | |
self.assertIsInstance(s.month, Month) | |
self.assertEqual(s.month, Month(2021, 9)) | |
o = TestModel.get(TestModel.month == Month(2021, 10)) | |
self.assertIsInstance(o.month, Month) | |
self.assertEqual(o.month, Month(2021, 10)) | |
n = TestModel.get(TestModel.month == '2021-11') | |
self.assertIsInstance(n.month, Month) | |
self.assertEqual(n.month, Month(2021, 11)) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment