Django 使用max()选择最近的活动时间

Django 使用max()选择最近的活动时间,django,Django,我的文章模型有注释外键和脚注, 我想检索最新活动的时间来操纵文章,或者添加新评论,或者添加新脚注 article = get_object_or_404(Article, pk=pk) #retrieve the article's updated time latest_article_date_updated = article.date_updated #retrieve the latest footnote's created time footnotes = article.fo

我的文章模型有注释外键和脚注,
我想检索最新活动的时间来操纵文章,或者添加新评论,或者添加新脚注

article = get_object_or_404(Article, pk=pk)  
#retrieve the article's updated time
latest_article_date_updated = article.date_updated
#retrieve the latest footnote's created time
footnotes = article.footnote_set.all()
latest_footnote_date_created = footnotes.last().date_created
#retrieve the latest comment time
latest_comment_date_updated = article.comment_set.order_by("-date_updated").first().date_updated
然后选择最大值作为最新值

article_active_time = max(latest_article_date_updated,
                          latest_footnote_date_created,
                          latest_comment_date_updated)
它报告错误

Exception Value:    
'NoneType' object has no attribute 'date_created'
我试图用计算机解决这个问题

latest_footnote_date_created = footnotes.last().date_created or 0
latest_comment_date_updated = article.comment_set.first().date_updated or 0
article_active_time = max(latest_article_date_updated,
                          latest_footnote_date_created,
                          latest_comment_date_updated)
它报告打字错误

TypeError: '>' not supported between instances of 'int' and 'datetime.datetime'

如何选择最新的活动时间来操作文章?

您需要将默认设置为
datetime.datetime
对象,而不是
0

解决方案

# depends on what your max should be when `date_created` / `date_updated`
# comes out as `None`.
out_of_range_date = datetime.datetime(2000, 1, 1)

latest_footnote_date_created = footnotes.last().date_created or out_of_range_date
latest_comment_date_updated = article.comment_set.first().date_updated or out_of_range_date