Skip to content

Instantly share code, notes, and snippets.

@collinanderson
Created October 21, 2011 18:10
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 collinanderson/1304529 to your computer and use it in GitHub Desktop.
Save collinanderson/1304529 to your computer and use it in GitHub Desktop.
serialize_object
def serialize_object(obj):
args = []
for field in obj._meta.fields:
value = field.value_from_object(obj)
if value and value != field.default:
from decimal import Decimal
if isinstance(value, unicode):
try:
value = str(value)
except UnicodeEncodeError:
pass
if isinstance(value, (long, Decimal)) and value == int(value):
value = int(value)
if isinstance(value, list):
value = [clean(x) for x in value]
args.append('%s=%r' % (field.attname, value))
return '%s(%s)' % (type(obj).__name__, ', '.join(args))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment