Django meta admin 排序 - 排除语法冠词

2 投票
3 回答
992 浏览
提问于 2025-04-17 09:21

我现在有一段模型代码:

class Book(models.Model):
    title = models.CharField(max_length=100)
    num_pages = models.IntegerField(blank=True, null=True)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ["title"]

如果我有一本书的标题,比如《The Fry Chronicles》或者《A Hitchhikers Guide to the Galaxy》,有没有办法让Django在管理界面中忽略这些短小的词(比如an, a, the等),只按照后面的单词来排序结果呢?

更进一步,是否可以把结果排成这样:

  • Fry Chronicles, The
  • Hitchhikers Guide to the Galaxy, A

也就是说,把这些短小的词放到书名的最后面?

有没有人能提出解决这两个问题的办法呢?

提前谢谢大家!

3 个回答

-1

不知道这样是否有效……还没有测试过……只是一个想法,记住Django其实就是Python……希望这能帮助你走上正确的道路!

def splitter(title):  
    list_title=[]
    a = split(title)    
        for word in a:
            if len(word) > 3: # With this you filter "a" "the" etc. but not "Bob" etc.!!
               word.append(list_title)
    return list_tile


class Meta:
    ordering = splitter(title) # not sure if this is working....
2

你可以试试这个:

class Book(models.Model):
    displayed_title = models.CharField(max_length=100)
    ordered_title = models.CharField(max_length=100)

    def __unicode__(self):
        return self.displayed_title

    class Meta:
        ordering = ["ordered_title"]

并且要确保在存储之前先处理一下 ordered_title

1

我觉得这件事不太可能做到,除非你去修改Django后台的内部代码。

不过,如果你不介意有点重复的话,可以用一个小技巧。你可以在书籍(Book)里加一个额外的字段,用来表示排序的标题(比如叫 clean_title),然后在后台使用 ordering 属性 来进行排序。

撰写回答