Last active
March 16, 2016 16:50
-
-
Save chriscauley/181dce6e6ed72f823d27 to your computer and use it in GitHub Desktop.
First attempt at creating a script to migrate from parse (mongodb) to django
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
import json, datetime, math, os | |
model_names = ['Subscription'] | |
for model_name in model_names: | |
with open("%s.json"%model_name,'r') as f: | |
subscriptions = json.loads(f.read()) | |
fields = {} | |
max_lengths = {} | |
nulls = {} | |
assert(subscriptions.keys() == ['results']) | |
for subscription in subscriptions['results']: | |
for key,value in subscription.items(): | |
fields[key] = value | |
max_lengths[key] = max(max_lengths.get(key,0),len(str(value))) | |
if value == None: | |
nulls[key] = value | |
field_list = [] | |
class_names = { | |
'int': 'IntegerField', | |
'bool': 'BooleanField', | |
'unicode': "CharField", | |
'datetime': 'DateTime', | |
'dict': "CharField", | |
} | |
print "class %s(models.Model):"%model_name | |
for key,value in sorted(fields.items()): | |
field_type = str(type(value)).split(u"'")[1] | |
init_kwargs = "" | |
try: | |
datetime.datetime.strptime(value.split(".")[0],"%Y-%m-%dT%H:%M:%S") | |
field_type = "datetime" | |
except: | |
pass | |
python_class = class_names[field_type] | |
max_length = 2**int(math.log(max_lengths[key],2)+1) | |
if key in nulls: | |
init_kwargs += "null=True,blank=True," | |
if python_class == "DateTime" and key == "updatedAt": | |
init_kwargs += "auto_now=True," | |
if python_class == "CharField": | |
init_kwargs += "max_length=%s,"%max_length | |
print "\t%s = models.%s(%s)"%(key,python_class,init_kwargs) | |
#print "{:>30} {:10} {}\t{}".format(key,field_type,max_lengths[key],max_length) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment