Skip to content

Instantly share code, notes, and snippets.

@theY4Kman
Created October 4, 2018 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theY4Kman/6876c8148780c1450813f4d175ebe21c to your computer and use it in GitHub Desktop.
Save theY4Kman/6876c8148780c1450813f4d175ebe21c to your computer and use it in GitHub Desktop.
A Django ORM Subquery Expression which only returns the specified fields
from django.db.models import Subquery
class SubquerySelect(Subquery):
"""Return only a subset of fields from a Subquery"""
template = '(SELECT %(fields)s FROM (%(subquery)s) AS %(subquery_alias)s)'
def __init__(self, queryset, output_field=None, fields=('*',), **extra):
self.fields = tuple(fields)
extra['fields'] = ', '.join(fields)
extra.setdefault('subquery_alias', 'subquery')
super().__init__(queryset, output_field=output_field, **extra)
def copy(self):
clone = super().copy()
clone.fields = self.fields
return clone
def get_source_expressions(self):
return super().get_source_expressions() + list(self.fields)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment