Skip to content

Instantly share code, notes, and snippets.

View jmichalicek's full-sized avatar

Justin Michalicek jmichalicek

View GitHub Profile
@jmichalicek
jmichalicek / django_order_by_list.py
Created June 17, 2019 12:16
Django ORM select and order based on pre-ordered list of ids
# I can never remember that this is a thing, but it is occasionally useful for me
ids = [5, 2, 3, 1, 4]
order = Case(*[When(id=id, then=pos) for pos, id in enumerate(ids)])
queryset = MyModel.objects.filter(id__in=ids).order_by(order)
import logging
import time
from contextlib import ContextDecorator
class log_execution_time(ContextDecorator):
"""
A context processor and decorator for logging timings.
logger = logging.getLogger(__name__)
@log_execution_time('my_func', logger, logging.DEBUG)