【发布时间】:2022-11-22 17:19:31
【问题描述】:
我想显示每天有多少帖子,所以我写了这段代码:
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:
这是模型.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() 的无效文字:b'15 16:24:10.577648'
【问题讨论】:
-
没有解决你的错误,但你不能从注释中的日期时间中提取日期并以此为基础吗?
-
更改后是否已正确迁移
-
@ManojTolagekar 是的,在进行这些更改后我已经迁移了
-
@TrueGopnik 你能解释一下吗?
-
我在回答中解释了使用代码格式
标签: django django-models django-views