Created
November 20, 2019 13:42
-
-
Save franciscoafonsoo/5dab9570ff6a97a068e72a74e5b87a92 to your computer and use it in GitHub Desktop.
utilities to return all fields and values from Django Model objects
This file contains 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 get_all_fields(obj): | |
""" | |
return a {field:value} dict for a Django Model object | |
lambda equivelent. useful for pasting in idle | |
list_fields = lambda obj: {f.name: getattr(obj, f.name) for f in obj._meta.fields} | |
""" | |
return {f.name: getattr(obj, f.name) for f in obj._meta.fields} | |
def get_all_fields_queryset(qs): | |
""" | |
return a generator in which each value is {field:value} | |
of a Django Model object in a given Django QuerySet | |
lambda equivelent. useful for pasting in idle | |
list_queryset = lambda qs: ({f.name: getattr(obj, f.name) for f in obj._meta.fields} for obj in qs) | |
usage: | |
>>> foo = list_queryset(django_queryset) | |
>>> next(foo) | |
""" | |
return ({f.name: getattr(obj, f.name) for f in obj._meta.fields} for obj in qs) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment