Skip to content

Instantly share code, notes, and snippets.

@josephmosby
Created February 16, 2015 17:37
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 josephmosby/7ac22f01ccf738e94d7a to your computer and use it in GitHub Desktop.
Save josephmosby/7ac22f01ccf738e94d7a to your computer and use it in GitHub Desktop.
import pymongo
from django.db.models import Model
from django.db.models.fields.files import ImageFieldFile
from django.conf import settings
def get_mongo_db():
client = pymongo.MongoClient(settings.MONGO_DB_HOST, settings.MONGO_DB_PORT)
db = client.test
return db
def convert_fields(model):
"""
Recursive function to iterate over all fields in a Model.
If the field is a ForeignKey, ManyToManyField or OneToOneField,
go into the model and recursively store fields.
"""
fields = model._meta.get_all_field_names()
update_fields = {}
for field in fields:
try:
field_value = getattr(model, field)
if getattr(field_value, 'all', None):
"""
Branch for a ManyToManyField.
Iterate over each Model in and append data to a list.
Add list to dictionary.
"""
fk_list = []
for fk_model in field_value.all():
fk_list.append(convert_fields(fk_model))
update_fields[field] = fk_list
elif isinstance(field_value, Model):
"""
Branch for a ForeignKey or OneToOneField.
Create data for the Model and add to dictionary.
"""
update_fields[field] = convert_fields(field_value)
elif isinstance(field_value, ImageFieldFile):
"""
Serialize an ImageField.
"""
try:
update_fields[field] = field_value.path
except ValueError:
"""
ValueError occurs if there is no actual File (i.e., is null).
"""
update_fields[field] = ""
else:
"""
Branch for a standard field.
Add data to the dictionary.
"""
if field == "id":
update_fields["pg_" + model._meta.verbose_name + "_id"] = field_value
else:
update_fields[field] = field_value
except AttributeError:
"""
ManyToManyFields will throw an AttributeError when trying to reference the parent.
"""
pass
return update_fields
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment