我有主题中心模型:
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()
返回导致错误消息的[]
。
有谁能帮我解决这个逻辑吗?
发布于 2014-06-10 15:18:10
我假设您也在其他地方使用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()
用于其他任何事情,那么您应该直接将这个逻辑放入该函数中。
发布于 2014-06-10 13:25:53
你可以通过改变你的条件来尝试
if not book and not journal:
#Action you want to perform
或者您可以查看lastone
列表是否为空,您可以在其中追加任何消息,如
if not len(lastone):
#Your code to append a message
https://stackoverflow.com/questions/24140823
复制相似问题