Created
December 14, 2011 19:28
-
-
Save mattrobenolt/1478076 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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