我的文章模型具有注释和脚注的外键,
我想检索最新活动的时间来操纵文章,添加新评论或添加新脚注。
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
TypeError: '>' not supported between instances of 'int' and 'datetime.datetime'
如何选择最近的活动时间来操纵文章?
答案 0 :(得分:1)
您需要将默认对象设置为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