Home > other >  "invalid literal for int() with base 10:" error while changing DateTimeField to DateField
"invalid literal for int() with base 10:" error while changing DateTimeField to DateField

Time:11-22

I want to show how many posts are being made each day so i wrote this code:

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

This code is working but since created is a DateTimeField it groups the data depending on both date and time so for example (2022, 11, 15, 16, 24, 10, 577648) and (2022, 11, 15, 16, 40, 39, 224605) are in the same day but in different Time.

so in order to fix this i've changed DateTimeField to DateField:

Here is the 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

and now i get this error after this change:

invalid literal for int() with base 10: b'15 16:24:10.577648'

CodePudding user response:

Annotating date and grouping by that using 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},
    )
  • Related