Ejemplo n.º 1
0
def model_to_dict(instance,
                  fetch_related=False,
                  fields=None,
                  exclude_many_to_many=False,
                  json=False):
    """
    Take given model instance and return a dict containing all model
    properties.
    """
    if not fields:
        fields = get_model_field_names(
            instance.__class__,
            exclude_many_to_many=exclude_many_to_many,
            json=json)

    # general fields
    result = django_model_to_dict(instance, fields=fields)

    # related managers
    if fetch_related:
        for fieldname in fields:
            p = getattr(instance, fieldname)
            if 'django.db.models.fields.related_descriptors.ManyRelatedManager' in unicode(
                    p.__class__):
                result[fieldname] = p.all()

    return result
Ejemplo n.º 2
0
def model_to_dict(instance, expand=""):
    """Convert model and sub models in expand to dict."""
    if expand is None:
        expand = ""

    to_expand = expand.split(',')
    if expand != '' and not isinstance(to_expand, list):
        to_expand = [to_expand]

    for idx, entry in enumerate(to_expand):
        to_expand[idx] = entry.split('.')

    to_expand_first_words = [elem[0] for elem in to_expand]

    instance_dict = django_model_to_dict(instance)

    for key in instance_dict.keys():
        value = instance_dict[key]
        key_indices = [  # indices of expands started by key
            idx for idx, elem in enumerate(
                to_expand_first_words
            ) if elem == key
        ]
        related_sub_expands = [  # navigate through each expand path starting by key
            val[1:] for idx, val in enumerate(to_expand) if idx in key_indices
        ]

        # may be a foreignkey field as django_model_to_dict convert foreignkey as int value
        if isinstance(value, int):
            instance_value = getattr(instance, key)

            # is a model and is in expand
            if (
                isinstance(instance_value, Model) and  # is django model instance
                key in to_expand_first_words  # asked to be expanded
            ):
                instance_dict[key] = model_to_dict(
                    instance_value,
                    expand=",".join(
                        related_sub_expands[0]
                    )
                )

        if isinstance(value, list):
            if key in to_expand_first_words:  # asked to be expanded
                for idx, sub_value in enumerate(value):
                    if isinstance(sub_value, Model):  # is django model instance
                        instance_dict[key][idx] = model_to_dict(
                            sub_value,
                            expand=",".join(
                                related_sub_expands[0]
                            )
                        )
            else:
                for idx, sub_value in enumerate(value):
                    if isinstance(sub_value, Model):  # is django model instance
                        instance_dict[key][idx] = sub_value.id

    return instance_dict
Ejemplo n.º 3
0
def model_to_dict(instance, max_depth=5, depth=0, *args, **kw):
    if isinstance(instance, models.Model):
        return instance.to_dict()
    if isinstance(instance, dict):
        return instance
    if not hasattr(instance, '_meta'):
        return None

    opts = instance._meta
    depth += 1
    data = django_model_to_dict(instance, *args, **kw)
    fields = kw.get('fields') or []
    exclude = kw.get('exclude') or []
    for field_name in opts.get_all_field_names():
        if fields and field_name in fields:
            continue
        if exclude and field_name in exclude:
            continue
        _cached_key = '_%s_cache' % field_name
        field = opts.get_field_by_name(field_name)[0]
        if field.__class__.__name__ in ('DateTimeField', 'DateField',
                                        'TimeField'):
            value = getattr(instance, field_name)
            data[field_name] = None
            if value or value == datetime.time(0, 0):
                if field.__class__.__name__ == 'DateTimeField':
                    data[field_name] = value.strftime('%Y-%m-%d %H:%M:%S')
                else:
                    data[field_name] = value.isoformat()
        elif field.__class__.__name__ == 'ForeignKey':
            if _cached_key in instance.__dict__:
                if depth >= max_depth:
                    continue
                data[field_name] = {}
                try:
                    value = getattr(instance, field_name)
                except (ObjectDoesNotExist, AttributeError):
                    continue
                data[field_name] = model_to_dict(value, depth=depth)
        elif field.__class__.__name__ in ('RelatedObject', 'ManyToManyField'):
            if field_name in data:
                del data[field_name]
        else:
            data[field_name] = field.value_from_object(instance)

    return data
Ejemplo n.º 4
0
def model_to_dict(instance, max_depth=5, depth=0):
    if isinstance(instance, dict):
        return instance
    if not hasattr(instance, '_meta'):
        return None

    opts = instance._meta
    depth += 1
    data = django_model_to_dict(instance)

    for field_name in opts.get_all_field_names():
        _cached_key = '_%s_cache' % field_name
        field = opts.get_field_by_name(field_name)[0]
        if field.__class__.__name__ in ('DateTimeField', 'DateField',
                                        'TimeField'):
            value = getattr(instance, field_name)
            data[field_name] = None
            if value:
                if field.__class__.__name__ == 'DateTimeField':
                    data[field_name] = value.strftime('%Y-%m-%d %H:%M:%S')
                else:
                    data[field_name] = value.isoformat()
        elif field.__class__.__name__ == 'ForeignKey':
            if _cached_key in instance.__dict__:
                if depth >= max_depth:
                    continue
                data[field_name] = {}
                try:
                    value = getattr(instance, field_name)
                except (ObjectDoesNotExist, AttributeError):
                    continue
                data[field_name] = model_to_dict(value, depth=depth)
        elif field.__class__.__name__ in ('RelatedObject', 'ManyToManyField'):
            if field_name in data:
                del data[field_name]
        else:
            data[field_name] = field.value_from_object(instance)

    return data