Django-model_to_dict的用法
def model_to_dict(instance, fields=None, exclude=None):
"""
Return 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, return only the
named.
``exclude`` is an optional list of field names. If provided, exclude the
named from the returned dict, even if they are listed in the ``fields``
argument.
"""
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 is not None and f.name not in fields:
continue
if exclude and f.name in exclude:
continue
data[f.name] = f.value_from_object(instance)
return data
from django.forms.models import model_to_dict
di = model_to_dict(order, exclude=['create_time', 'update_time'])
源码函数声明:def model_to_dict(instance, fields=None, exclude=None):
其中参数instance是对象实例,fields是指定需要哪些字段,exclude是指定排除哪些字段,exclude比fields优先级高。
这样查到某个实例后懒得去看model定义就可以直接用这个方法看有哪些字段了
重点:此时字典只包含django对象的直接对象
此model_to_dict函数不返回带有editable=False(因为它用于表单)的字段.
相关资料:
如何将Django Model对象转换为字典并仍然拥有其外键?

浙公网安备 33010602011771号