eegloo
eegloo

Reputation: 1499

How to sort records in python?

I am fetching records from table.

This is My class:

class user_guide(db.Model):
    ugq_no = db.IntegerProperty()
    ug_quest = db.TextProperty()    
    ug_answer = db.TextProperty()    
    ug_parent_type = db.TextProperty()  
    last_modified_on = db.DateTimeProperty(auto_now=True)
    class Meta:
        db_table = 'user_guide'
        verbose_name = 'User Guides'
        verbose_name_plural = 'User Guide'
    def __unicode__(self):
        return str(self.ugq_no)

Following is function.

def get_all_record(request):        
    qry_obj = db.Query(user_guide)   
    all_list = []
    #Here I am fetching all records from qry_obj. In this I am getting data in random order.
    for q in qry_obj: 
        all_list.append(q)         
        #all_list.sort()
        sorted(all_list)      

    return HttpResponse(serializers.serialize('json', all_list), mimetype='application/json')

In this I am taking all the records from qry_obj and adding those record in all_list.

But I want to sort data in ascending order with respect to ugq_no . I tried sort() and sorted() but no use. (Django Framwork, python) Where I am going wrong,please help?

Upvotes: 3

Views: 703

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121914

Use the .order method on the query to have the Google datastore sort your records for you:

qry_obj = db.Query(user_guide).order('ugq_no')

Note that the user_guide object itself gives you access to the query too:

qry_obj = user_guide.all().order('ugq_no')

You can turn the query into a list simply by calling list on it:

all_list = list(qry_obj)

Upvotes: 3

Related Questions