def get_dict_from_obj(obj):
obj_dict = obj.__dict__<EOL>obj_dict_result = obj_dict.copy()<EOL>for key, value in obj_dict.items():<EOL><INDENT>if key.endswith('<STR_LIT>'):<EOL><INDENT>key2 = key.replace('<STR_LIT>', '<STR_LIT>')<EOL>try:<EOL><INDENT>field, model, direct, m2m = obj._meta.get_field_by_name(key2)<EOL>if isinstance(field, ForeignKey):<EOL><INDENT>obj_dict_result[key2] = obj_dict_result[key]<EOL>del obj_dict_result[key]<EOL><DEDENT><DEDENT>except FieldDoesNotExist:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>manytomany_list = obj._meta.many_to_many<EOL>for manytomany in manytomany_list:<EOL><INDENT>pks = [obj_rel.pk for obj_rel in manytomany.value_from_object(obj).select_related()]<EOL>if pks:<EOL><INDENT>obj_dict_result[manytomany.name] = pks<EOL><DEDENT><DEDENT>return obj_dict_result<EOL>
Edit to get the dict even when the object is a GenericRelatedObjectManager.
Added the try except.