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的方式做爲返回值,因此大多數的時候咱們也不太會想到它,以致於我都忘了他,然而卻不能忽略擁有它的方便.python