You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I sometimes need to make object comparable to each other and define a custom order. For example some records should be orderable by an enduser.
Up to now I always wrote some custom logic for every project. Now I decided to make it a bit more abstract and universal.
I thought about something like this:
fromsqlalchemyimportfunc, Column, Integerfromsqlalchemy.engine.defaultimportDefaultExecutionContextfromsqlalchemy.sql.expressionimportselectfromsqlalchemy.sql.selectableimportSelectfromsqlalchemy.engine.baseimportEnginefromsqlalchemy.engine.resultimportRowProxydefdefault_order_index(context: DefaultExecutionContext) ->int:
""" Get the current highest index for each model """ifcontext:
engine: Engine=context.enginetry:
query: Select=select([func.max(1, func.max(context.current_column.table.c.order_index) +1)])
r: RowProxy=engine.execute(query).fetchone()
i: int=int(r[0])
returniexcept (TypeError, IndexError):
return0else:
return0classOrderableMixin(object):
""" Mixin to make database models comparable. -- The highest object has the lowest index (e.g. ZERO (0)) The lowest object has the highest index (.e.g INF (9999999999)) """order_index=Column(Integer,
default=default_order_index,
index=True)
@classmethoddefnormalize(cls) ->None:
""" Normalize all order indexes """foridx, iteminenumerate(cls.query.order_by(cls.order_index).all()):
item.order_index=idxdefmove_up(self) ->None:
""" Move the database object one up -> decreases index by one"""ifself.order_index==0:
return# get all items ordered by their indexitems=self.query.order_by(self.__class__.order_index).all()
idx=items.index(self)
# swap with item aboveabove=items[idx-1]
above.order_index, self.order_index=idx, above.order_indexdefmove_down(self) ->None:
""" Move the database object one down -> increases index by on"""# get all items ordered by their indexitems=self.query.order_by(self.__class__.order_index).all()
idx=items.index(self)
# if item is last do nothingifidx==len(items) -1:
return# swap with item belowbelow=items[idx+1]
below.order_index, self.order_index=idx, below.order_index
Hey there!
I sometimes need to make object comparable to each other and define a custom order. For example some records should be orderable by an enduser.
Up to now I always wrote some custom logic for every project. Now I decided to make it a bit more abstract and universal.
I thought about something like this:
This could then be used as follows:
What do you guys think about that?
The text was updated successfully, but these errors were encountered: