Created
July 18, 2011 21:49
-
-
Save allanlei/1090756 to your computer and use it in GitHub Desktop.
Django Serialization for Jquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Django serialization via wadofstuff's Django serializers to convert models into Javascript objects using Jquery. wadofstuff's serializers converts models into a JSON string where each model is a JSON Object with attributes "extras", "fields", "pk", and "model". This script converts the JSON object into something similar to what you find in python ie instance.pk, instance.get_absolute_url, instance.my_related_model.myField | |
Optional setup: | |
$.ajaxSetup({ | |
cache: false, | |
converters: { | |
"text django-json": $.parseDjangoJSON | |
} | |
}); | |
Usage: | |
$.getDjangoJSON(url, aoData, function(models, status, xhr){ | |
//Do something with the models(models is an array) | |
/* | |
[{ | |
pk: 123124, | |
Meta: { | |
model: "myapp.mymodel" | |
}, | |
my_related_model: { | |
myField: "Hello", | |
}, | |
get_absolute_url: "/my/object/url", | |
__unicode__: "something something" | |
}, | |
...] | |
*/ | |
}); | |
getDjangoJSON does the same thing as getJSON but with dataType="django-json" which converts the response to a django model |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($){ | |
$.getDjangoJSON = function(url, data, success){ | |
return $.ajax({ | |
url: url, | |
dataType: "django-json", | |
data: data, | |
success: success | |
}); | |
}; | |
$.parseDjangoJSON = function(data, options){ | |
var settings = $.extend({ | |
modelName: "model" | |
}, options); | |
var data = $.parseJSON(data); | |
return $.map(data, function(modelData, index){ | |
return {model: $.toDjangoFormat(modelData)}; | |
}); | |
}; | |
$.toDjangoFormat = function(oData){ | |
if(!$.isPlainObject(oData) || oData["model"] == null || oData["pk"] == null) return null; | |
var model = $.extend({ | |
pk: oData["pk"], | |
Meta: { | |
model: oData["model"] | |
} | |
}, oData["fields"], oData["extras"]); | |
$.each(model, function(attr, data){ | |
if($.isPlainObject(data) && data["model"] && data["pk"]){ | |
model[attr] = $.toDjangoFormat(data); | |
} | |
}); | |
return model; | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment