Skip to content

Instantly share code, notes, and snippets.

@mattrobenolt
Created December 14, 2011 19:28
Show Gist options
  • Save mattrobenolt/1478076 to your computer and use it in GitHub Desktop.
Save mattrobenolt/1478076 to your computer and use it in GitHub Desktop.
def qs_to_dict(qs, exclude=(), func=None):
return [model_to_dict(model, exclude, func) for model in qs]
def model_to_dict(model, exclude=(), func=None):
result = {}
fields = [field.name for field in model._meta.fields if field.name not in exclude]
if callable(func):
for field in fields:
key = func(field)
if key:
result[key] = getattr(model, field)
else:
for field in fields:
result[field] = getattr(model, field)
return result
def my_filter(key):
if key in ('id', 'email'):
return key.upper()
else:
# return None to not be included
return None
qs_to_dict(User.objects.all(), exclude=('avatar',), func=my_filter)
qs_to_dict(User.objects.all(), func=lambda field: field.upper())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment