Skip to content

Instantly share code, notes, and snippets.

@balazs-endresz
balazs-endresz / models.py
Last active April 3, 2024 22:58
analyze explain django queryset
from django.db import connections
from django.db.models.query import QuerySet
def explain(self):
cursor = connections[self.db].cursor()
cursor.execute('set enable_seqscan = off')
query, params = self.query.sql_with_params()
print(query % params)
cursor.execute('EXPLAIN ANALYZE %s' % query, params)
@balazs-endresz
balazs-endresz / .py
Last active February 12, 2024 15:15
Order queryset by list of IDs
# https://stackoverflow.com/questions/4916851/django-get-a-queryset-from-array-of-ids-in-specific-order/37648265#37648265
from django.db.models import Case, When
pk_list = [10, 2, 1]
preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pk_list)])
queryset = MyModel.objects.filter(pk__in=pk_list).order_by(preserved)
# pre django 1.8:
@balazs-endresz
balazs-endresz / gist:f9b27514046506a7db75
Created December 2, 2014 09:34
Drop all tables and sequences in postgres
# tables for owned by 'tableowner'
select 'drop table if exists "' || tablename || '" cascade;' from pg_tables where tableowner='tableowner';
# all sequences
select 'drop sequence if exists "' || relname || '" cascade;' from pg_class where relkind = 'S';
export function throttleDebouncePromise(
inner,
{ throttle, debounce, cache, immediateIfCached },
) {
// Ordinary debounce functions cause issues with promises and react-select but this works well.
// Based on: https://stackoverflow.com/questions/35228052/debounce-function-implemented-with-promises
const resolveCallbacks = []
const store = {}
let timeout = null
let time = new Date()
@balazs-endresz
balazs-endresz / storage.py
Last active August 20, 2018 22:22
ManifestStaticFilesStorage with source maps, and ignoring missing files
from django.contrib.staticfiles.storage import ManifestStaticFilesStorage
class ManifestStaticFilesStorageWithSourceMaps(ManifestStaticFilesStorage):
"""
Adds js and css source map support for ManifestStaticFilesStorage.
"""
patterns = (
("*.css", (
@balazs-endresz
balazs-endresz / .py
Created March 21, 2018 20:44
Constant memory streaming CSV writer (works with prefetch_related too)
def generator_from_queryset(queryset, chunksize=2000, enumerate=False):
assert queryset.query.order_by is not None
offset = 0
i = 0
finished = False
while not finished:
finished = True
for row in queryset[offset:offset + chunksize]:
finished = False
if enumerate:
@balazs-endresz
balazs-endresz / .py
Created September 26, 2017 14:23
cast and round django database functions
from django.db.models import ExpressionWrapper, FloatField, Func
class Cast(Func):
function = 'CAST'
template = '%(function)s(%(expressions)s AS %(db_type)s)'
def __init__(self, expression, db_type):
# convert second positional argument to kwarg to be used in function template
super(Cast, self).__init__(expression, db_type=db_type)
@balazs-endresz
balazs-endresz / gist:5050df80015cdf443f01
Created April 7, 2015 14:34
Wagtail rich text editor paragraph issue fix
(function(){
// hallo.js plugin to use paragraphs by default
// https://github.com/bergie/hallo/issues/157
// https://github.com/torchbox/wagtail/issues/559
function getLastChildElement(el){
var lc = el.lastChild;
while(lc && lc.nodeType != 1) {
if(lc.previousSibling)
lc = lc.previousSibling;
@balazs-endresz
balazs-endresz / slack-hide-status-bar.user.js
Last active December 15, 2016 12:05
Hide status bar on Slack
// ==UserScript==
// @name Hide status bar on Slack
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://*.slack.com/*
// @grant none
// ==/UserScript==
@balazs-endresz
balazs-endresz / .sh
Created September 8, 2016 14:36
send email if new entry is made to kern.log
#!/bin/bash
# http://serverfault.com/questions/24428/monitoring-dmesg-output
MAILTO=root
LOG=/var/log/kern.log
OFFSET_FILE=$0.offset