我想显示每天有多少帖子被发表,所以我写了这段代码:
class ServerInsightsView(View):
def get(self, request, server_tag):
server = Server.objects.get(tag=server_tag)
post_daily_count =server.posts.all().values('created').annotate(dailycount=Count('created')).order_by() #to get the number of posts each day depending on the DateTimeField
return render(request, 'servers/insights.html', {'server':server, 'post_daily_count': post_daily_count})
此代码可以正常工作,但由于created
是DateTimeField
,因此它会根据日期和时间对数据进行分组,例如,(2022,11,15,16,24,10,577648)和(2022,11,15,16,40,39,224605)在同一天,但在不同的Time
中。
为了解决这个问题,我将DateTimeField
更改为DateField
:
以下是models.py:
class Post(models.Model):
title = models.CharField(max_length=200)
text = models.TextField(null=True, blank=True)
saved = models.ManyToManyField(User, blank=True, related_name='saves')
upvotes = models.ManyToManyField(User, blank=True, related_name='upvotes')
downvotes = models.ManyToManyField(User, blank=True, related_name='downvotes')
votes_count = models.IntegerField(default=0)
server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name='posts')
creator = models.ForeignKey(User , on_delete=models.CASCADE, related_name='posts', null=True)
created = models.DateField(auto_now_add=True) #was DateTimeField
updated = models.DateField(auto_now=True) #was DateTimeField
现在我得到这个错误后,这个变化:
**对于基数为10的int()无效的文字:1999年12月15日
1条答案
按热度按时间41zrol4v1#
使用TruncDate注解日期并按日期分组: