Skip to content

Instantly share code, notes, and snippets.

@jineshpaloor
Created October 2, 2016 13:47
Show Gist options
  • Select an option

  • Save jineshpaloor/a2dfef9cbf9061b19ee87aedb47b603c to your computer and use it in GitHub Desktop.

Select an option

Save jineshpaloor/a2dfef9cbf9061b19ee87aedb47b603c to your computer and use it in GitHub Desktop.

Revisions

  1. jineshpaloor created this gist Oct 2, 2016.
    50 changes: 50 additions & 0 deletions mongoengine_detailed_dict.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    mport datetime
    import mongoengine

    from invoicing.const import DATE_FORMAT


    black_listed_fields = [
    "auth_token", "avatar", "deleted_at", "google_id", "last_login_at", "password"
    ]


    def format_to_detailed_dict(obj):
    """Receive mongoengine model dict and create a detailed dict
    which contains the details of all reference fields.
    :param obj: mongodb model object
    :return dictionary: detailed dictionary which contains of all
    referenced fields.
    """
    data = {}
    fields = obj._fields.items()

    # for each field in object
    for k, v in fields:
    if obj._class_name == "User" and k in black_listed_fields:
    continue
    # if field is reference field, convert that into dict first
    if not obj[k]:
    data[k] = obj[k]
    continue

    if isinstance(v, mongoengine.fields.ReferenceField):
    data[k] = format_to_detailed_dict(obj[k])
    # if field is datetime instance, convert to string
    elif isinstance(v, mongoengine.fields.DateTimeField):
    data[k] = obj[k].strftime(DATE_FORMAT)
    # if field is List iterate through each instance of list and repeat the same
    elif isinstance(v, mongoengine.fields.ListField):
    data[k] = [format_to_detailed_dict(x) for x in obj[k]]
    elif isinstance(v, mongoengine.fields.DictField):
    data[k] = dict(obj[k])
    for sk, sv in obj[k].items():
    if isinstance(sv, datetime.datetime):
    data[k][sk] = sv.strftime(DATE_FORMAT)
    elif hasattr(sv, '_is_document') and sv._is_document:
    data[k][sk] = format_to_detailed_dict(obj[k][sk])
    else:
    data[k] = str(obj[k])

    return data