1
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

二十一
1.4k 声望867 粉丝

无论遇到多大的困难,你总是能扛过去,坚持一件事,对自己