Django model_to_dict的一个问题

自定义model_to_dict()方法,在model里面加上一个方法

def to_dict(self):
       opts = self._meta
       data = {}
       for f in opts.concrete_fields:
           value = f.value_from_object(self)
           if isinstance(value, datetime):
               value = value.strftime('%Y-%m-%d %H:%M:%S')
           elif isinstance(f, FileField):
               value = value.url if value else None
           data[f.name] = value
       return data
"""
Why is `__fields` in here?
    it holds the list of fields except for the one ends with a suffix '__[field_name]'.
    When converting a model object to a dictionary using this method,
    You can use a suffix to point to the field of ManyToManyField in the model instance.
    The suffix ends with '__[field_name]' like 'publications__name'
"""
__fields = list(map(lambda a: a.split('__')[0], fields or []))

for f in chain(opts.concrete_fields, opts.virtual_fields, opts.many_to_many):
    is_edtiable = getattr(f, 'editable', False)

    if fields and f.name not in __fields:
        continue

    if exclude and f.name in exclude:
        continue

    if isinstance(f, ManyToManyField):
        if instance.pk is None:
            data[f.name] = []
        else:
            qs = f.value_from_object(instance)
            if qs._result_cache is not None:
                data[f.name] = [item.pk for item in qs]
            else:
                try:
                    m2m_field  = list(filter(lambda a: f.name in a and a.find('__') != -1, fields))[0]
                    key = m2m_field[len(f.name) + 2:]
                    data[f.name] = list(qs.values_list(key, flat=True))
                except IndexError:
                    data[f.name] = list(qs.values_list('pk', flat=True))

    elif isinstance(f, DateTimeField):
        date = f.value_from_object(instance)
        data[f.name] = date_to_strf(date) if date_to_strf else date_to_timestamp(date)

    elif isinstance(f, ImageField):
        image = f.value_from_object(instance)
        data[f.name] = image.url if image else None

    elif isinstance(f, FileField):
        file = f.value_from_object(instance)
        data[f.name] = file.url if file  else None

    elif is_edtiable:
        data[f.name] = f.value_from_object(instance)

"""
Just call an instance's function or property from a string with the function name in `__fields` arguments.
"""
funcs = set(__fields) - set(list(data.keys()))
for func in funcs:
    obj = getattr(instance, func)
    if inspect.ismethod(obj):
        data[func] = obj()
    else:
        data[func] = obj
return data
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,238评论 25 708
  • 每个程序员都会有自己的编码习惯,但是几乎每个项目,各个公司都会有自己的编码规范,开发软件是一个团队活动,不能搞个人...
    饥人谷_鲁晋阅读 998评论 1 0
  • 前几天一直在看张皓宸的《谢谢自己够勇敢》,虽然他的文字并没有刻意去煽情,但我总是从他的字里行间中感受到了微微的感动...
    礼雪晶阅读 1,230评论 0 14
  • 周六周天两天我出差了,儿子去了姥姥家,周一早上去接儿子上幼儿园时,儿子见到我第一句话就是:“妈妈,你以后别东跑西跑...
    粒芳阅读 320评论 0 2
  • 由于种种原因,简书等第三方平台博客不再保证能够同步更新,欢迎移步 GitHub:https://github.co...
    萌面大道阅读 551评论 0 1

友情链接更多精彩内容