1. ホーム
  2. パイソン

Django モデルオブジェクトをjsonデータに変換する方法

2022-03-02 13:05:09
#The original method: take all the properties and put them into the dict one by one, but of course you can refer to method 2, which extracts all the properties and values of the object
#Reference method 1: simple version
def convert_to_dicts(objs):
    '''Convert a list of objects to a list of dictionaries'''
    obj_arr = []
     
    for o in objs:
        # Convert Object objects to Dict
        dict = {}
        dict.update(o.__dict__)
        dict.pop("_state", None) # remove the extra fields
        obj_arr.append(dict)
     
    return obj_arr


call: convert_to_dicts(modelName.objects.filter(id=1)) # must be an array, non-array needs to be improved
#Reference method 2: adds date type determination
def convert_obj_to_dicts(model_obj):
    import inspect, types
    
    object_array = []
     
    for obj in model_obj:
# obj.last_update_time = obj.last_update_time.isoformat()
# obj.create_time = obj.create_time.isoformat()
        # Get all properties
        field_names_list = obj._meta.get_all_field_names()
        print field_names_list
        for fieldName in field_names_list:
            try:
                fieldValue = getattr(obj, fieldName) # Get the attribute value
                print fieldName, "--", type(fieldValue), "--", hasattr(fieldValue, "__dict__")
                if type(fieldValue) is datetime.date or type(fieldValue) is datetime.datetime:
    # fieldValue = fieldValue.isoformat()
                    fieldValue = datetime.datetime.strftime(fieldValue, '%Y-%m-%d %H:%M:%S')
                # Didn't think of a solution for foreign keys with cache fields
# if hasattr(fieldValue, "__dict__"):
# fieldValue = convert_obj_to_dicts(model_obj)
            
                setattr(obj, fieldName, fieldValue)
# print fieldName, "\t", fieldValue
            except Exception, ex:
                print ex
                pass
        # Convert the Object object to a Dict first
        dict = {}
        dict.update(obj.__dict__)
        dict.pop("_state", None) # This removes the extra fields from the model object
        object_array.append(dict)
    print object_array
    
    return object_array


call: convert_obj_to_dicts(modelName.objects.filter(id=1)) # must be an array, non-array needs to be improved

#Reference to method 3
from django.core import serializers
print serializers.serialize("json", modelName.objects.filter(id=32)) #non-array doesn't seem to work either





#Reference method 1: simple version
def convert_to_dicts(objs):
    '''Convert a list of objects to a list of dictionaries'''
    obj_arr = []
     
    for o in objs:
        # Convert Object objects to Dict
        dict = {}
        dict.update(o.__dict__)
        dict.pop("_state", None) # remove the extra fields
        obj_arr.append(dict)
     
    return obj_arr


call: convert_to_dicts(modelName.objects.filter(id=1)) # must be an array, non-array needs to be improved


#Reference method 2: adds date type determination
def convert_obj_to_dicts(model_obj):
    import inspect, types
    
    object_array = []
     
    for obj in model_obj:
# obj.last_update_time = obj.last_update_time.isoformat()
# obj.create_time = obj.create_time.isoformat()
        # Get all properties
        field_names_list = obj._meta.get_all_field_names()
        print field_names_list
        for fieldName in field_names_list:
            try:
                fieldValue = getattr(obj, fieldName) # Get the attribute value
                print fieldName, "--", type(fieldValue), "--", hasattr(fieldValue, "__dict__")
                if type(fieldValue) is datetime.date or type(fieldValue) is datetime.datetime:
    # fieldValue = fieldValue.isoformat()
                    fieldValue = datetime.datetime.strftime(fieldValue, '%Y-%m-%d %H:%M:%S')
                # Didn't think of a solution for foreign keys with cache fields
# if hasattr(fieldValue, "__dict__"):
# fieldValue = convert_obj_to_dicts(model_obj)
            
                setattr(obj, fieldName, fieldValue)
# print fieldName, "\t", fieldValue
            except Exception, ex:
                print ex
                pass
        # Convert the Object object to a Dict first
        dict = {}
        dict.update(obj.__dict__)
        dict.pop("_state", None) # This removes the extra fields from the model object
        object_array.append(dict)
    print object_array
    
    return object_array


call: convert_obj_to_dicts(modelName.objects.filter(id=1)) # must be an array, non-array needs to be improved


#Reference to method 3
from django.core import serializers
print serializers.serialize("json", modelName.objects.filter(id=32)) #non-array doesn't seem to work either



私はpythonの初心者です、上記は参考程度にしてください、もしもっと良い案があれば、もっとアドバイスをお願いします


上記の方法2において、オブジェクトがクラスであるかどうかの判断は様々な方法で試されましたが、外部キーがどのレベルに行くかを自動的に検出するなど、モデルオブジェクトから余分な属性を自動的に削除することはまだ行われていません。