django之model_to_dict

def model_to_dict(instance, fields=None, exclude=None):
    """
    Returns a dict containing the data in ``instance`` suitable for passing as
    a Form's ``initial`` keyword argument.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned dict.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned dict, even if they are listed in
    the ``fields`` argument.
    """
    from django.db import models
    opts = instance._meta
    data = {}
    for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):    
        if not getattr(f, 'editable', False):
            continue
        if fields and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        data[f.name] = f.value_from_object(instance)
        # Evaluate ManyToManyField QuerySets to prevent subsequent model
        # alteration of that field from being reflected in the data.
        if isinstance(f, models.ManyToManyField):
            data[f.name] = list(data[f.name])
    return data
    
@total_ordering
@python_2_unicode_compatible
class Field(RegisterLookupMixin):
        # "省略其他代码..."
        def value_from_object(self, obj):
        """
        Returns the value of this field in the given model instance.
        """
            return getattr(obj, self.attname)

上面是django中model_to_dict的源码,通过注释我们可以非常的明白这个方法的作用,然而在实体项目中,因为习惯了构造dict的方式作为返回值,所以大多数的时候我们也不太会想到它,以至于我都忘了他,然而却不能忽略拥有它的方便.

使用场景

  • 在模型类字段很多且需要全部返回或大部分都需要返回的时候
  • 只使用model中的几个字段值,而又不常用的modelview
    原文作者:二十一
    原文地址: https://segmentfault.com/a/1190000019565728
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞