Exemple #1
0
def model_to_dict(instance, fields=None, exclude=None):
    """
    Customized wrapper for Django's built-in model_to_dict(). Does the following:
      - Excludes the instance ID field
      - Exclude any fields prepended with an underscore
      - Convert any assigned tags to a comma-separated string
    """
    _exclude = ["id"]
    if exclude is not None:
        _exclude += exclude

    model_dict = _model_to_dict(instance, fields=fields, exclude=_exclude)

    for key in list(model_dict.keys()):
        if key.startswith("_"):
            del model_dict[key]
        elif key == "tags":
            model_dict[key] = ",".join(sorted([tag.name for tag in model_dict["tags"]]))
        # Convert ManyToManyField to list of instance PKs
        elif (
            model_dict[key]
            and type(model_dict[key]) in (list, tuple)
            and hasattr(model_dict[key][0], "pk")
        ):
            model_dict[key] = [obj.pk for obj in model_dict[key]]

    return model_dict
Exemple #2
0
def model_to_dict(instance, fields=None, exclude=None):
    """
    Customized wrapper for Django's built-in model_to_dict(). Does the following:
      - Excludes the instance ID field
      - Exclude any fields prepended with an underscore
      - Convert any assigned tags to a comma-separated string
    """
    _exclude = ['id']
    if exclude is not None:
        _exclude += exclude

    model_dict = _model_to_dict(instance, fields=fields, exclude=_exclude)

    for key in list(model_dict.keys()):
        if key.startswith('_'):
            del model_dict[key]

        # TODO: Differentiate between tags assigned to the instance and a M2M field for tags (ex: ConfigContext)
        elif key == 'tags':
            model_dict[key] = ','.join(
                sorted([tag.name for tag in model_dict['tags']]))

        # Convert ManyToManyField to list of instance PKs
        elif model_dict[key] and type(
                model_dict[key]) in (list, tuple) and hasattr(
                    model_dict[key][0], 'pk'):
            model_dict[key] = [obj.pk for obj in model_dict[key]]

    return model_dict
def model_to_dict(instance, fields, api=False):
    """
    Returns a dictionary representation of an instance.
    """
    model_dict = _model_to_dict(instance, fields=fields)

    # Map any additional (non-field) instance attributes that were specified
    for attr in fields:
        if hasattr(instance, attr) and attr not in model_dict:
            model_dict[attr] = getattr(instance, attr)

    for key, value in list(model_dict.items()):
        try:
            field = instance._meta.get_field(key)
        except FieldDoesNotExist:
            continue

        if value and type(field) in (ManyToManyField, TaggableManager):
            model_dict[key] = sorted([o.pk for o in value])

        if api and type(value) in (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Interface,
                ipaddress.IPv6Interface,
        ):
            model_dict[key] = str(value)

    return model_dict
Exemple #4
0
def model_to_dict(*args, rename={}, **kwargs):
    """Custom version that knows how to deal with the types used in Django models."""
    result = _model_to_dict(*args, **kwargs)
    # Round-trip through JSON using DjangoJSONEncode to get rid of problematic fields
    result = json.loads(
        json.dumps(result, sort_keys=True, indent=1, cls=DjangoJSONEncoder))
    # Rename fields if any.
    for from_, to in rename.items():
        result[to] = result[from_]
        del result[from_]
    return result
def model_to_dict(obj, *a, **kw):
    extra_fields = kw.pop('extra_fields', ())

    as_dict = _model_to_dict(obj, *a, **kw)
    as_dict.update({
        extra: getattr(obj, extra)
        for extra in extra_fields if hasattr(obj, extra)
    })

    for k, v in as_dict.items():
        as_dict[k] = to_simple_types(v)

    return as_dict
Exemple #6
0
def model_to_dict(instance: object, exclude_pk: bool = True) -> dict:
    """Converts model instance into a dictionary"""
    raw = _model_to_dict(instance)
    data = {}
    for field in instance._meta.get_fields():
        if field.name in raw:
            if isinstance(field, ManyToManyField):
                data[field.name] = [obj.pk for obj in raw[field.name]]
            elif isinstance(field, FileField):
                data[field.name] = str(raw[field.name])
            elif not exclude_pk or field.name != instance._meta.pk.name:
                data[field.name] = raw[field.name]
    return data
Exemple #7
0
def model_to_dict_with_date_support(m):
    d = _model_to_dict(m)
    for k, v in d.items():
        if isinstance(v, datetime):
            v = apidate.convert_datetime_to_iso_string(v)
    return d