zoukankan      html  css  js  c++  java
  • python model对象转为dict数据


    在接口通讯里经常遇到这种需求,需要将对象的字段名和值均传至接口,
    user = User.objects.get(id=1)

    笨方法1,没错,我这样写过:
    di = {}
    di['username'] = user.username
    di['email'] = user.email
    ...... # 诸多赋值

    笨方法2,没错,我也这样写过:
    di = {}
    all_fields = User._meta.get_all_field_names()
    special_fields = ['is_active', 'is_stuff']
    for i in special_fields:
        try:
            all_fields.remove(i)
        except:
            pass
    for field in all_fields:
        di[field] = getattr(user, field)

    !!!正确的方法,翻源码时遇到的,最喜欢这种命名,看名字就知道了怎样用和返回值,看到它时又感觉django暖暖的,很贴心~:
    from django.forms.models import model_to_dict
    di = model_to_dict(user, exclude=['is_active', 'is_stuff'])

    源码:def model_to_dict(instance, fields=None, exclude=None):
    参数instance是对象实例,fields是指定需要哪些字段,exclude是指定排除哪些字段,exclude比fields优先级高。

  • 相关阅读:
    JS定时循环
    JS分组
    中位数 题解
    NOIP2017 D2T3 题解
    CF949E Binary Cards 题解
    友善的树形DP
    300英雄的危机(heroes)
    [北京省选集训2019]图的难题 题解
    洛谷 P1268 树的重量 题解
    洛谷 P2633 Count on a tree 题解
  • 原文地址:https://www.cnblogs.com/zknublx/p/6180430.html
Copyright © 2011-2022 走看看