I am trying to display the value A,B,C or D as per the total of a blogger. But I am getting the error - Cannot resolve keyword 'total' into field.Can someone suggest the correct way of doing it. Thanks
models.py
class Blog(models.Model):
author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blogs')
likes = models.ManyToManyField(User, blank=True, related_name='blog_likes')
title = models.CharField(max_length=100)
def total_likes_received(user):
return user.blogs.aggregate(total_likes=Count('likes'))['total_likes'] or 0
@property
def total(self):
return count(self.author.title) + count(self.author.likes)
views.py
def get_queryset(self):
return (Blog.objects.filter(date__lte=timezone.now())
.order_by('date')
.annotate(
name=Case(
When(total__gt=0,total__lte=11, then=Value('B')),
When(total__gt=10,total__lte=21, then=Value('C')),
When(total__gt=20,total__lte=31, then=Value('D')),
default=Value('A'),
output_field=CharField(),
),
).values_list('name')
)
You Must also Using Django F()
and Count()
annotate functions...
Try Below code:
Blog.objects.annotate(
author_titles=Count('author__title'),
author_likes=Count('author__likes')
).annotate(
total=F('author_titles') + F('author_likes')
).annotate(
name=Case(
When(total__gt=0,total__lt=11, then=Value('B')),
When(total__gt=10,total__lt=21, then=Value('C')),
When(total__gt=20,total__lt=31, then=Value('D')),
default=Value('A'),
output_field=CharField(),
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With