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