www.un.org/Depts/DGACM/index_spanish.htm 简短问题: Django是否有办法,根据某些领域的字母顺序,以不敏感的方式找到下一行?
www.un.org/Depts/DGACM/index_french.htm 我在数据库中有几句话,并对它们有详细的看法。 我谨按字母顺序逐字逐句。 因此,我需要按字母顺序列出前言和下字。 现在我做的是:
class Word(models.Model):
original = models.CharField(max_length=50)
...
def neighbours(self):
"""
Returns the words adjacent to a given word, in alphabetical order
"""
previous_words = Word.objects.filter(
original__lt=self.original).order_by( -original )
next_words = Word.objects.filter(
original__gt=self.original).order_by( original )
previous = previous_words[0] if len(previous_words) else None
next = next_words[0] if len(next_words) else None
return previous, next
问题是,这确实是一种对案件敏感的比较,例如<代码>。 Foo见bar
,这不是我想要的。 为了避免这一问题,在另一个观点中——在我列举所有话时,我已经利用了增加额外领域的习惯模式主管。
class CaseInsensitiveManager(models.Manager):
def get_query_set(self):
"""
Also adds an extra lower field which is useful for ordering
"""
return super(CaseInsensitiveManager, self).get_query_set().extra(
select={ lower : lower(original) })
and in the definition of Word I add
objects = models.Manager()
alpha = CaseInsensitiveManager()
这样,我就能够提出问题。
Word.alpha.all().order_by( lower )
并按字母顺序读取所有字,不论情况如何。 但Icannot do
class Word(models.Model):
original = models.CharField(max_length=50)
...
objects = models.Manager()
alpha = CaseInsensitiveManager()
def neighbours(self):
previous_words = Word.objects.filter(
lower__lt=self.lower()).order_by( -lower )
next_words = Word.objects.filter(
lower__gt=self.lower()).order_by( lower )
previous = previous_words[0] if len(previous_words) else None
next = next_words[0] if len(next_words) else None
return previous, next
确实,Django将不接受fieldviewupsextrafield。 因此,我应该做些什么(没有书写KQ习俗)?
www.un.org/Depts/DGACM/index_spanish.htm Bonus questions: 我在做些什么时至少会看到更多的问题。 首先,我不相信业绩。 我假定,在I下定义previous_words
和next_words
时,根本不发生任何疑问。 当我界定<代码>previous和next
时,数据库中唯一一个查询方式将发生,产生一个或多个疑问。
SELECT Word.original, ..., lower(Word.original) AS lower
WHERE lower < `foo`
ORDER BY lower DESC
LIMIT 1
这项权利吗? 或者,我做些什么会使数据库过于缓慢? 我不知道有关Django ORM内部工作的足够细节。
The second problem is that I actually have to cope with words in different languages. Given that I know the language for each word, is there a way to get them in alphabetical order even if they have non-ASCII characters. For instance I d want to have méchant
, moche
in this order, but I get moche
, méchant
.