Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

django snippet 800

from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.query import QuerySet

def maybe_call(x):
    if callable(x): return x()
    return x


class JSONEncoder(DjangoJSONEncoder):
    '''An extended JSON encoder to handle some additional cases.

    The Django encoder already deals with date/datetime objects.
    Additionally, this encoder uses an 'as_dict' or 'as_list' attribute or
    method of an object, if provided. It also makes lists from QuerySets.
    '''
    def default(self, obj):
        if hasattr(obj, 'as_dict'):
            return maybe_call(obj.as_dict)
        elif hasattr(obj, 'as_list'):
            return maybe_call(obj.as_list)
        elif isinstance(obj, QuerySet):
            return list(obj)
        return super(JSONEncoder, self).default(obj)
json_encode = JSONEncoder().encode
Comment

PREVIOUS NEXT
Code Example
Python :: how to set default value in many2one 
Python :: TypeError: Object of type DictProxy is not JSON serializable 
Python :: Python - Comment vérifier une corde est vide 
Python :: landscape odoo report 
Python :: python calander from Programmer of empires but updated 
Python :: shutdown thread python 
Python :: pandas cummax 
Python :: Spatial Reference arcpy 
Python :: Third step creating python project 
Python :: run persistent py script in background (good for flask) 
Python :: python you bad 
Python :: image segmentation pyimagesearch 
Python :: spearman correlation seaborn 
Python :: index operator in python without input 
Python :: Make Latest pyhton as default in mac 
Python :: select nth item from list 
Python :: list example in python 
Python :: "DO_NOTHING" is not defined django 
Python :: how to make api check multiple status using drf 
Python :: list of thing same condition 
Python :: custom Yolo object detection python 
Python :: nlp generate parse tree in python 
Python :: first_last6 
Python :: pandas show head and tail 
Python :: what should I do when the keras image datagenerato is nit working 
Python :: which is best between c and python for making application 
Python :: python time range monthly 
Python :: fetch member by id discord.py 
Python :: make my own rabbit bomb using python 
Python :: Python regex emailadres no jpg 
ADD CONTENT
Topic
Content
Source link
Name
4+4 =