• Django中重写model_to_dict方法,兼容接口返回展示时间和外键的


    from itertools import chain
    import datetime
    from django.db.models.fields.related import ManyToManyField, ForeignKey, OneToOneField
    from django.core.files import File
    
    
    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.
        """
        if instance == None:  # 若果要是过来空的值,那就直接返回了
            return
        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
            print('看看F是啥:', f)
            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)
            value = f.value_from_object(instance)
            if type(value) == datetime.datetime:
                value = value.strftime('%Y-%m-%d %H:%M:%S')
            elif type(value) == datetime.date:
                value = value.strftime('%Y-%m-%d ')
            elif type(f) == ForeignKey:  # 展示外键关联表的数据
                foreign_Key = getattr(instance, f.name)
                value = model_to_dict(foreign_Key)
            elif type(f) == OneToOneField:  # 展示一对一关联表的数据
                opneToOne_Field = getattr(instance, f.name)
                value = model_to_dict(opneToOne_Field)
            elif type(f) == ManyToManyField:  # 展示多对多的
                many_to_many__list = [model_to_dict(item) for item in value]
                value = many_to_many__list
            if isinstance(value, File):  # /XXX/XXX/a.jpg  返回文件的路径
                value = str(value)
            data[f.name] = value
        return data
    
  • 相关阅读:
    面试官:我看你简历上写了MySQL,对MySQL InnoDB引擎的索引了解吗?
    QA26\28
    Hystrix Turbine聚合监控
    【ARM微型电脑/IoT设备/嵌入式】Linux Ubuntu 树莓派 Jetson nano设置PTP时间同步
    TypeScript中的declare关键字
    Java学习总结(答案版)
    2011年03月16日 Go生态洞察:Go朝着更高稳定性迈进
    实战:如何优雅地扩展Log4j配置?
    动态改变列数做分页
    mac安装redis及springboot整合redis,简单快速
  • 原文地址:https://blog.csdn.net/qq_37605109/article/details/127702405