Python django - 如何按名称字段的第一个字母按字母顺序对对象进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/16778819/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
django - how to sort objects alphabetically by first letter of name field
提问by doniyor
I have a model which has the fields wordand definition. model of dictionary. 
我有一个模型,其中包含字段word和definition. 字典模型。
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?
我想在视图中制作它,而不是在模板中。这在 Django 中怎么可能?
采纳答案by Aya
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 wordfield if the type is TextField, so sorting by wordwill take a long time if there are a lot of rows in your table.
但是,word如果类型为,您将无法在字段上创建索引TextField,因此word如果表中有很多行,排序依据将需要很长时间。
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 wordcolumn, but also ensure you can't define the same word twice.
...这不仅会在word列上创建索引,还会确保您不能两次定义同一个词。
回答by Krumelur
Since you tagged your question Django, I will answer how to do it using Django entities.
既然你标记了你的问题 Django,我将回答如何使用 Django 实体来做到这一点。
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)

