Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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?

like image 797
doniyor Avatar asked May 27 '13 18:05

doniyor


People also ask

How do I sort objects in Django?

Django has order_by method to sort the queryset in ascending and descending order. You can order the queryset on any field. In the Django model, there is one autogenerated 'id' field. You can use any of the fields (id name, mobile or name) to sort the queryset.


Video Answer


1 Answers

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.

like image 56
Aya Avatar answered Oct 21 '22 16:10

Aya