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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,381評論 25 708
  • 每個程序員都會有自己的編碼習(xí)慣,但是幾乎每個項目,各個公司都會有自己的編碼規(guī)范,開發(fā)軟件是一個團隊活動,不能搞個人...
    饑人谷_魯晉閱讀 918評論 1 0
  • 前幾天一直在看張皓宸的《謝謝自己夠勇敢》,雖然他的文字并沒有刻意去煽情,但我總是從他的字里行間中感受到了微微的感動...
    禮雪晶閱讀 1,162評論 0 14
  • 周六周天兩天我出差了,兒子去了姥姥家,周一早上去接兒子上幼兒園時,兒子見到我第一句話就是:“媽媽,你以后別東跑西跑...
    粒芳閱讀 274評論 0 2
  • 由于種種原因,簡書等第三方平臺博客不再保證能夠同步更新,歡迎移步 GitHub:https://github.co...
    萌面大道閱讀 493評論 0 1