Wizard
Wizard

Reputation: 22093

Select the latest activity time using max()

My article model has foreign-key of comment and footnote,
I'd like to retrieve the latest activity's time to manipulate the article either add new comment or add new footnote.

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

Then select the max as the latest

article_active_time = max(latest_article_date_updated,
                          latest_footnote_date_created,
                          latest_comment_date_updated)

It report error

Exception Value:    
'NoneType' object has no attribute 'date_created'

I tried to solve the problem by

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)

It report TypeError

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

How do I select the latest activity time to manipulate the article?

Upvotes: 0

Views: 22

Answers (1)

Sachin
Sachin

Reputation: 3674

You need to set the default as datetime.datetime object, not 0.

Solution:

# 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

Upvotes: 1

Related Questions