将www.example.com中的DateTimeField更改为DateField时出现“int()的文字无效(基数为10):“错误models.py| Django

0aydgbwb  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(150)

我想显示每天有多少帖子被发表,所以我写了这段代码:

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})

此代码可以正常工作,但由于createdDateTimeField,因此它会根据日期和时间对数据进行分组,例如,(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日

41zrol4v

41zrol4v1#

使用TruncDate注解日期并按日期分组:

from django.db.models.functions import TruncDate

class ServerInsightsView(View):
def get(self, request, server_tag):
    server = Server.objects.get(tag=server_tag)
    post_daily_count = (
        server.posts.all()
        .annotate(date=TruncDate('created'))
        .values('date')
        .annotate(dailycount=Count('date'))
        .order_by()
    )
    return render(
        request,
        'servers/insights.html',
        {'server': server, 'post_daily_count': post_daily_count},
    )

相关问题