Search code examples
pythondjangotastypie

Tastypie and JSON Field serialization issue


So I read the following posts without finding the answer:

My model is using a JSONField to store arbitrary data.

class Task(models.Model):
    """
        Execution of a Test
    """
    results = JSONField(max_length=1000, blank=True)

In a python shell, I can print this field and it is rendering the following:

[{"name": "tata", "result": "toto"}]

I modify dehydrate method to remove unicode, but I have the following result:

**Dehydrate Method:**
def dehydrate_results(self, bundle):
    results = json.dumps(bundle.obj.results)
    return results 

**Tastypie Result**
"results": "[{\"name\": \"Cash In\", \"result\": \"toto\"}]"

I can't use this object in my javascript app... Maybe you can explain me how to have a "normal" json output from tastypie:

**Wanted Tastypie Result**
"results": [{"name": "Cash In", "result": "toto"}]

Thanks.


Solution

  • If I'm not mistaken, you don't need to provide a custom dehydrate field since bundle.obj.results is already a deserialized object from the database.

    Rather than provide a custom dehydrate_results function, simply specify the results field type as being either a tastypie.fields.DictField or a tastypie.fields.ListField depending on the data you're storing.

    eg.

    from tastypie.fields import ListField
    
    class MyResource(ModelResource):
        results = ListField(attribute='results')