Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Case in django

Tags:

python

django

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')
            )
like image 788
user Avatar asked Jul 04 '18 02:07

user


1 Answers

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(),
    )
)
like image 121
M.javid Avatar answered Nov 17 '22 02:11

M.javid