Django排序对象需要一些logi方面的帮助

2024-05-13 03:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有Topiccenter模型:

class TopicCenter(models.Model):
  title = models.TextField()      
  def latest_entry(self):
    latest_entries = []
    book = self.tc_books.order_by('-id')[:1]
    journal = self.tc_journals.order_by('-id')[:1]
    if book: 
        for b in book:
            if b:
                latest_entries.append(b)
    if journal: 
        for jn in journal: 
            if jn: 
                latest_entries.append(jn)
    lastone = []
    if latest_entry:            
        lastone = max(latest_entries, key = lambda x: x.added)
    return lastone
    # what to return here if lastone is empty list ?? :(

每个主题中心可以有许多书籍和期刊。我想通过added字段获取最新条目。你知道吗

我现在正在按最新条目的日期对主题中心进行排序。现在我面临的问题是,一些主题中心完全是空的(没有书,没有期刊),所以我不知道如果latest_entry[]的话,在latest_entry()方法中返回什么,所以我可以这样使用它:

tcss = TopicCenter.objects.all().distinct('id')  
sorter = lambda x: x.latest_entry().added
tcs = sorted(tcss, key=sorter, reverse=True)

此时我得到了'list' object has no attribute 'added',因为一个主题中心既没有书也没有期刊,所以latest_entry()返回[],这导致了错误消息。你知道吗

有人能帮我解决这个逻辑吗


Tags: selfid主题addedif中心latestjournal
2条回答

你可以试着改变你的条件

if not book and not journal:
    #Action you want to perform

或者您可以查看lastone列表是否为空,您可以在其中附加任何消息,如

if not len(lastone):
    #Your code to append a message

我假设您也在其他地方使用latest_entry(),所以只需创建另一个方法latest_added_time(),它返回latest_entry.added或假时间。你知道吗

class TopicCenter(models.Model):
    ...
    def latest_added_time(self):
        latest = self.latest_entry()
        if latest:
            return latest.added
        else:
            # returns a time to place it at the end of the sorted list
            return datetime(1, 1, 1) 

然后,您可以使用这种新方法进行排序:

tcss = TopicCenter.objects.all().distinct('id')  
sorter = lambda x: x.latest_added_time()
tcs = sorted(tcss, key=sorter, reverse=True)

如果您没有将latest_entry()用于其他任何东西,那么您应该将此逻辑直接放入该函数中。你知道吗

相关问题 更多 >