Skip to content

Instantly share code, notes, and snippets.

@7mp
Last active December 18, 2015 03:09
Show Gist options
  • Save 7mp/5716322 to your computer and use it in GitHub Desktop.
Save 7mp/5716322 to your computer and use it in GitHub Desktop.
Circumventing (legacy) Django's need to add `extra`'s `select`s to GROUP BY.
# -*- coding: utf-8 -*-
# TODO FIXME HARD-CODING KLUDGE MONKEYS PATCHING EACH OTHER
# Django (1.2 at least), I DON'T LIKE YOU
class FakeSQLUnicode(unicode):
def as_sql(*args, **kwargs):
# See django.db.models.sql.compiler, get_grouping, the place with `hasattr(col, 'as_sql')
# MySQL GROUP BY doesn't work with COALESCE() in GROUP BY,
# failing with Database error 1111, "invalid use of group function".
# Solution: convert the aggregate to the `id` which is there anyway! :D
return '`store_product`.`id`'
extra_select = FakeSQLUnicode('''
COALESCE(
MIN(`store_variation`.`discount_price`),
MIN(`store_variation`.`price`)
)''')
additional_select = 'lowest_available_price'
products = products.annotate(
# Unused annotation to skip manual joins
min_normal_price=Min('variations__price'),
).extra(select={'lowest_available_price': extra_select}).order_by(
'lowest_available_price'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment