我有一个方法叫postState()
. 此方法应该检查帖子的状态。帖子可以有 3 种状态(新、旧、存档),该方法将帖子作为其参数。该方法根据过去的天数计算状态。
- 30 天前的帖子是新的
- 30 - 60 天前的帖子已过时
- 一个 > 60 天的旧帖子已存档
这是代码:
#This method automatically determines the state of the post. Whether it is (New, Old, or # Archived)
#The method takes in one parameter which is the post itself
#the method compares the date of which the post was published in and the current date
#It then uses an algorithim to determine the difference in number of days between the current date and the published date
#Based on the amount returned, if the amount is less than 30 days, the state = "NEW", if between 30 and 60, the state = "OLD", if greater than 60, the state = "ARCHIVED"
def postState(self):
current_time = datetime.datetime.now()
p = Post.objects.get(id = self.id)
#used if the current year is greater than the year of the published post
if current_time.year > self.pub_Date.year:
#this is in case for exmaple the published month of the post is December and the current month is January
#Although the years are diff yet the diff in days may not be greater than 30
#Ex: published date: 2012, 12, 28 ----- current date: 2013, 1, 10
if current_time.month == 1 and self.pub_Date.month ==12 and (current_time.day + (31 - self.pub_Date.day)) > 30:
p.state = 'Old'
p.save()
#this is in case for exmaple the published month of the post is November and the current month is January
#Although the years are diff yet the diff in days may not be greater than 30 and less than 60
#Ex: published date: 2012, 11, 1 ----- current date: 2013, 1, 28
elif current_time.month == 1 and self.pub_Date.month ==11 and (current_time.day + (31 - self.pub_Date.day)) < 60:
p.state = 'Old'
p.save()
else:
p.state = 'Archived'
p.save()
#Used when the current year and Published year of the post are the same
if current_time.year == self.pub_Date.year:
day_diff_diff_month = current_time.day + (31 - self.pub_Date.day)
day_diff_same_month = current_time.day - self.pub_Date.day
month_diff = current_time.month - self.pub_Date.month
if month_diff >= 1:
month_diff = month_diff - 1
total_diff = (month_diff*31) + day_diff_diff_month
else:
total_diff = day_diff_same_month
if total_diff > 30 and total_diff < 60:
p.state = 'Old'
p.save()
if total_diff > 60:
p.state = 'Archived'
p.save()
我希望在用户打开帖子页面(post.html)或启动网站时运行此方法。
提前致谢。