Last active
July 8, 2019 14:27
-
-
Save M0r13n/19bedbdb5c6afd0e77343ead8572eb43 to your computer and use it in GitHub Desktop.
Sqlalchemy Mixin class to make database models comparable and sortable by users.
This file contains hidden or 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
class OrderableMixin(object): | |
""" Mixin to make database models comparable """ | |
order_index = db.Column(db.Integer, default=_default_index, index=True) | |
@classmethod | |
def normalize(cls): | |
""" Normalize all order indexes """ | |
for idx, item in enumerate(cls.query.order_by(cls.order_index).all()): | |
item.order_index = idx | |
db.session.commit() | |
def move_up(self): | |
""" Move the database object one up""" | |
if self.order_index == 0: | |
return | |
# get all items ordered by their index | |
items = self.query.order_by(self.__class__.order_index).all() | |
idx = items.index(self) | |
# swap with item above | |
above = items[idx - 1] | |
above.order_index, self.order_index = idx, above.order_index | |
db.session.commit() | |
def move_down(self): | |
""" Move the database object one down""" | |
# get all items ordered by their index | |
items = self.query.order_by(self.__class__.order_index).all() | |
idx = items.index(self) | |
# if item is last do nothing | |
if idx == len(items) - 1: | |
return | |
# swap with item below | |
below = items[idx + 1] | |
below.order_index, self.order_index = idx, below.order_index | |
db.session.commit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment