Page 1 of 2 12 LastLast
Results 1 to 10 of 14

Thread: Django JSON serializer reader

  1. #1
    Ext User
    Join Date
    Mar 2007
    Posts
    13
    Vote Rating
    0
      0  

    Default Django JSON serializer reader

    Code:
    Ext.data.DjangoJsonReader = function(meta, recordType){
        Ext.data.DjangoJsonReader.superclass.constructor.call(this, meta, recordType);
    };
    Ext.extend(Ext.data.DjangoJsonReader, Ext.data.JsonReader, {
        readRecords : function(o){
            this.jsonData = o;
            var s = this.meta;
        	var sid = s.id;
        	var recordType = this.recordType, fields = recordType.prototype.fields;
    
        	var totalRecords = 0;
        	if(s.totalProperty){
                var v = parseInt(eval("o." + s.totalProperty), 10);
                if(!isNaN(v)){
                    totalRecords = v;
                }
            }
            var records = [];
        	var root = s.root ? eval("o." + s.root) : o;
    	    for(var i = 0; i < root.length; i++){
    		    var n = root[i];
    	        var values = {};
    	        var id = (n[sid] !== undefined && n[sid] !== "" ? n[sid] : n['pk']);
    	        for(var j = 0, jlen = fields.length; j < jlen; j++){
    	            var f = fields.items[j];
    	            var map = f.mapping || f.name;
    	            var v = n['fields'][map] !== undefined ? n['fields'][map] : f.defaultValue;
    	            v = f.convert(v);
    	            values[f.name] = v;
    	        }
    	        var record = new recordType(values, id);
    	        record.json = n;
    	        records[records.length] = record;
    	    }
    	    return {
    	        records : records,
    	        totalRecords : totalRecords || records.length
    	    };
        }
    });

  2. #2
    Ext User
    Join Date
    May 2007
    Posts
    11
    Vote Rating
    0
      0  

    Default

    This is exactly what I am looking for! Except I can't figure out how to put it to use!

    If I use it as a reader for a data.Store, what parameters must I give this function?

    Thanks!

  3. #3
    Sencha User Animal's Avatar
    Join Date
    Mar 2007
    Location
    Bédoin/Nottingham
    Posts
    30,891
    Vote Rating
    89
      0  

    Default

    I haven't picked through the code closely, so I might have missed something crucial, but what does that do that makes it a DjangoJsonReader?

    Is it that it uses the property "fields" within the record object to get the mapped field from?

    In which case just use a mapping of "field.name" in you record definition, and use the standard JsonReader.

  4. #4
    Ext User
    Join Date
    May 2007
    Posts
    11
    Vote Rating
    0
      0  

    Default

    Django provides internal mechanisms for serializing python objects and django models. Here is an example from my application:

    Code:
    [{"pk": "1", "model": "jobs.job", "fields": {"status": 1, "contacts": [], "created_by": 1, "job_number": "", "bid_date": "2007-06-22 12:00:00", "created_on": "2007-03-15 09:59:42", "is_union": 1, "location": [3], "job_name": "Test Job"}}, {"pk": "2", "model": "jobs.job", "fields": {"status": 1, "contacts": [], "created_by": 1, "job_number": "", "bid_date": "2007-04-18 10:10:37", "created_on": "2007-03-19 10:10:57", "is_union": 1, "location": [3], "job_name": "Hawk Job"}}, {"pk": "3", "model": "jobs.job", "fields": {"status": 2, "contacts": [], "created_by": 3, "job_number": "", "bid_date": "2007-01-08 10:16:28", "created_on": "2007-03-19 10:17:06", "is_union": 1, "location": [6], "job_name": "Blah"}}]
    I had problems getting it the way Extjs wanted it in Django and ran along this. So I was thinking this took the above JSON and made it available for ExtJs to interpret. Maybe I am going about it all the wrong ways!

  5. #5
    Ext User
    Join Date
    Mar 2007
    Posts
    13
    Vote Rating
    0
      0  

    Default

    Quote Originally Posted by Animal View Post
    I haven't picked through the code closely, so I might have missed something crucial, but what does that do that makes it a DjangoJsonReader?

    Is it that it uses the property "fields" within the record object to get the mapped field from?

    In which case just use a mapping of "field.name" in you record definition, and use the standard JsonReader.
    Yes you right, i've just made it for laziness. And it will pickup the "id" from the "pk" field in Django's json output.

  6. #6
    Ext User
    Join Date
    Mar 2007
    Posts
    13
    Vote Rating
    0
      0  

    Default

    Quote Originally Posted by jakehawk View Post
    Django provides internal mechanisms for serializing python objects and django models. Here is an example from my application:

    Code:
    [{"pk": "1", "model": "jobs.job", "fields": {"status": 1, "contacts": [], "created_by": 1, "job_number": "", "bid_date": "2007-06-22 12:00:00", "created_on": "2007-03-15 09:59:42", "is_union": 1, "location": [3], "job_name": "Test Job"}}, {"pk": "2", "model": "jobs.job", "fields": {"status": 1, "contacts": [], "created_by": 1, "job_number": "", "bid_date": "2007-04-18 10:10:37", "created_on": "2007-03-19 10:10:57", "is_union": 1, "location": [3], "job_name": "Hawk Job"}}, {"pk": "3", "model": "jobs.job", "fields": {"status": 2, "contacts": [], "created_by": 3, "job_number": "", "bid_date": "2007-01-08 10:16:28", "created_on": "2007-03-19 10:17:06", "is_union": 1, "location": [6], "job_name": "Blah"}}]
    I had problems getting it the way Extjs wanted it in Django and ran along this. So I was thinking this took the above JSON and made it available for ExtJs to interpret. Maybe I am going about it all the wrong ways!
    This is a way you can do this.
    PHP Code:
    from django.http import HttpResponse
    from django
    .core import serializers

    def json_job_list
    (request):
        
    queryset Job.objects.all()
        
    root_name 'jobs' # or it can be queryset.model._meta.verbose_name_plural
        
    data '{"total": %s, "%s": %s}' % \
            (
    queryset.count(), root_nameserializers.serialize('json'queryset))
        return 
    HttpResponse(datamimetype='text/javascript;'
    And then in javascript
    PHP Code:
    var ds = new Ext.data.Store({
        
    proxy: new Ext.data.HttpProxy({url"/json/jobs/"}),
        
    reader: new Ext.data.DjangoJsonReader({
            
    root'jobs',
            
    totalProperty'total'
        
    }, [
            {
    name'job_name'},
            {
    name'status'}
        ])
    }); 
    If you use the Ext.data.JsonReader it will be something like this
    PHP Code:
    ds = new Ext.data.Store({
        
    proxy: new Ext.data.HttpProxy({url"/json/jobs/"}),
        
    reader: new Ext.data.JsonReader({
            
    root'jobs',
            
    totalProperty'total',
            
    id'pk'
        
    }, [
            {
    name'job_name'mapping'fields.job_name'},
            {
    name'status'mapping'fields.status'}
        ])
    }); 

  7. #7
    Sencha User trbs's Avatar
    Join Date
    Mar 2007
    Posts
    310
    Vote Rating
    0
      0  

    Default

    i like this

    yes, you can do it with JsonReader but it does feel good

    i would generalize the code in json_job_list list to:
    PHP Code:
    # webapp.json.serializer
    from django.core import serializers

    def Serialize
    (querysetroot_name=None):
        if 
    not root_name:
            
    root_name queryset.model._meta.verbose_name_plural
        
    return '{"total": %s, "%s": %s}' 
            (
    queryset.count(), root_nameserializers.serialize('json'queryset)) 
    PHP Code:
    # webapp.jobs.view
    from django.http import HttpResponse
    from webapp
    .json.serializer import Serialize
    from webapp
    .jobs.models import Job

    def json_job_list
    (request):
        return 
    HttpResponse(Serialize(Job.objects.all(), root_name='job'), mimetype='text/javascript'
    this is could also be easily converted to a generic url by:
    PHP Code:
    # webapp.genericviews

    from django.shortcuts import render_to_response
    from django
    .template import loaderRequestContext
    from django
    .http import HttpResponse
    from webapp
    .json.serializer import Serialize

    def json_simple_serialize
    (requestquerysetroot_name=None):
        return 
    HttpResponse(Serialize(querysetroot_name=root_name), mimetype='text/javascript'
    Which u can use in urls.py as:
    PHP Code:
    # webapps.jobs.urls

    from django.conf.urls.defaults import *
    from webapp.genericviews import json_simple_serialize
    from webapp
    .jobs.models import Job

    jobs_info_dict 
    = {
        
    'queryset':Job.objects.all(),
        
    'root_name''jobs'
    }
    urlpatterns patterns('',
        (
    r'json/jobs/'json_simple_serializejobs_info_dict),

    p.s. please note that trailing comma's don't hurt Python like they do with non-firefox? browsers in javascript.

  8. #8
    Ext User
    Join Date
    May 2007
    Posts
    11
    Vote Rating
    0
      0  

    Default

    Wow, great replies! Thanks guys, I will give this a shot today.

  9. #9
    Ext User
    Join Date
    Oct 2007
    Posts
    5
    Vote Rating
    0
      0  

    Default Problem in accessing the serialized data from Django.

    I am using the following code on the server side for Json conversion, as suggested by the previous threads:

    Code:
    queryset = LinkTags.objects.all()
    root_name = 'link_tag_list' 
    data = '{"total": %s, "%s": %s}' % (queryset.count(), root_name, serializers.serialize('json', queryset))
    return HttpResponse(data, mimetype='text/javascript;')
    "LinkTags" class has a single field named "tag_name". In the client side, I am retrieving in the following way:

    Code:
    var DataRecord = Ext.data.Record.create([
            {  name: 'tag_name', mapping: 'tag_name'} ]);
    var myReader = new Ext.data.JsonReader({
        root: 'link_tag_list',
        totalProperty: 'total',
        }, 
        DataRecord);
      var ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: "/project/save_test/?xhr"}),
        reader: myReader,
        remoteSort: true
        });
    However, being an Ajax newbie(and also ext), I am finding it difficult to access the data from this data structure on the client side. Basically, I need to iterate over all the "LinkTags" objects passed from server side and need to access the tag_name field of each object. I couldn't get any documentation help for this point onwards of the code. Can someone please tell me how to access this store data structure to actually iterate over the LinkTags objects and get tag_name field of each object?
    Last edited by bharath.keshav; 22 Oct 2007 at 11:25 PM. Reason: "LinkTags" class has a single field named "tag_name" not "tag_list"

  10. #10
    Ext User
    Join Date
    Oct 2007
    Posts
    5
    Vote Rating
    0
      0  

    Default

    Anyone there for help??

Page 1 of 2 12 LastLast

Similar Threads

  1. how to get access to a object from json-reader
    By humpdi in forum Ext 1.x: Help & Discussion
    Replies: 2
    Last Post: 21 Mar 2007, 12:22 AM
  2. Old reader.jsonData after a failed request
    By aconran in forum Ext 2.x: Help & Discussion
    Replies: 1
    Last Post: 7 Mar 2007, 7:12 PM
  3. rss feed reader in domino
    By gizzmo in forum Ext 1.x: Help & Discussion
    Replies: 0
    Last Post: 13 Nov 2006, 2:15 PM
  4. XML DOM serializer
    By rtoepfer in forum Ext 1.x: Help & Discussion
    Replies: 3
    Last Post: 8 Nov 2006, 10:24 AM
  5. Simple RSS reader seesm to be broken.
    By donalconlon in forum Ext 1.x: Bugs
    Replies: 1
    Last Post: 26 Sep 2006, 2:24 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •