[Django]-Django – how to sort objects alphabetically by first letter of name field

43👍

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.

👤Aya

8👍

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)

1👍

If you are using class based ListView

class WikiListView(ListView):
        model = Wiki
        template_name = # Path to your html code. Example: 'appName/htmlFileName.html

        def get_context_data(self, *args, **kwargs):
            wiki_list = Wiki.objects.order_by('word')
            context = super(WikiListView, self).get_context_data(*args, **kwargs)
            context["wiki_list"] = wiki_list
            return context

if you are using a simple view

def WikiView(request):
    wiki_list = Wiki.objects.order_by('word')
    return render(request, """HTML File""", {'wiki_list': wiki_list})

0👍

for example, I have an Article object that have a title field.

articles = list(sorted(articles, key=lambda obj:obj.title))

the issue you may run into is that you must require to return a QuerySet in class method occasions like get_queryset, the solution is stopping using a class based view and switch to a function view.

Leave a comment