Django: custom serialization options?

后端 未结 3 780
自闭症患者
自闭症患者 2021-02-10 23:12

I\'m working on a Django-based web service and I\'m trying to figure out what the best way to do my serialization will be.

The tricky requirement, though, is that I\'d l

3条回答
  •  旧时难觅i
    2021-02-10 23:47

    When I need some custom serialization really fast and my case doesn't require deserialization I just write django template that can make any format I want from list/queryset/object. You can then call render_to_string with proper context and you have your data serialized.

    UPDATE: some short example

    Let's say you want to get json format accepted by datatables.net plugin. Since there are some special parameters required serializing queryset using simplejson or sth else is impossible here (or might be not so easy at least). We found that fastest way to provide such structure is to create simple template like this one:

    {
        "sEcho": {{sEcho}},
        "iTotalRecords": {{iTotalRecords}},
        "iTotalDisplayRecords": {{iTotalDisplayRecords}},
        "aaData":[
        {% for obj in querySet %}
        [
            "{{obj.name}}",
            "{{obj.message|truncatewords:20}}",
            "{{obj.name}}"
        ]
        {% if not forloop.last %}
        ,
        {% endif %}
        {% endfor %}
        ]
    }
    

    which renders to beatiful json that we were looking for. It gives you full control over the format also. Other advantages is the abillity to modify objects fields by using built-in django filters which in our case was really usefull.

    I know this is not serialization as described in books but if f you want to convert some object to a custom format this solution might be the fastest one. For some reason django developers allowed to render template to any given format not only html, so why not to use it?

    Example shown above is very specific but you can generate any other format. Of course writing deserializer for that could restore object from this format might be painfull but if you don't need it...

提交回复
热议问题