django - how to sort objects alphabetically by first letter of name field


I have a model which has the fields word and definition. model of dictionary.

in db, i have for example these objects:

word          definition
Banana        Fruit
Apple         also Fruit
Coffee        drink

I want to make a query which gives me, sorting by the first letter of word, this:

Apple - also Fruit
Banana - Fruit    
Coffee -drink

this is my model:

class Wiki(models.Model):
   word = models.TextField() 
   definition = models.TextField()

I want to make it in views, not in template. how is this possible in django?

5/27/2013 7:10:26 PM

Accepted Answer

Given the model...

class Wiki(models.Model):
   word = models.TextField() 
   definition = models.TextField()

...the code...

my_words = Wiki.objects.order_by('word')

...should return the records in the correct order.

However, you won't be able to create an index on the word field if the type is TextField, so sorting by word will take a long time if there are a lot of rows in your table.

I'd suggest changing it to...

class Wiki(models.Model):
   word = models.CharField(max_length=255, unique=True) 
   definition = models.TextField()

...which will not only create an index on the word column, but also ensure you can't define the same word twice.

5/27/2013 8:12:54 PM

Since you tagged your question Django, I will answer how to do it using Django entities.

First, define your entity like:

class FruitWords(models.Model):
    word = models.StringField()
    definition = models.StringField()

    def __str__(self):
        return "%s - %s" % (self.word, self.definition)

To get the list:

for fruit in FruitWords.all_objects.order_by("word"):
    print str(fruit)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow