Django single table data of the serialized data serialization

A Type: serialized form data for

ret [ 'errors'] = obj.errors.as_data () 
Result = json.dumps (ret, CLS = JsonCustomEncoder) is customize #JsonCustomEncoder cls, in particular for converting ret field type error 
return HttpRespon (result)

Type II: Type queryset for serializing  

The first: v type is known 
    from django.core Import serializers 
     
    v = models.tb.objects.all () or # v = models.tb.objects.values ( 'id', 'name') v = list (v) 
    data = serializers.serialize ( "JSON", v) 
     
a second: type v are known, while not comprising the sequence of data, such as time, datetime other types, need to define CLS 
     
    Import JSON 
    from Import DATE datetime 
    from Import datetime datetime 
        
    class JsonCustomEncoder (json.JSONEncoder): 
         
        DEF default (Self, Field): 
          
            IF the isinstance (Field, datetime): 
                return field.strftime ( '% Y-M-% D%% H:% M :% S ') 
            elif the isinstance (Field, DATE): 
                return field.strftime (' M-%%% Y-D ') 
            the else: 
                return json.JSONEncoder.default (Self,field)
 
    v = models.tb.objects.values('id','name','ctime')
    v = list(v)
    v = json.dumps(v,cls=JsonCustomEncoder)

  

 

Guess you like

Origin www.cnblogs.com/supery007/p/12566692.html