-
-
Save josephmosby/7ac22f01ccf738e94d7a to your computer and use it in GitHub Desktop.
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 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