在django中使用Case

问题描述 投票:2回答:1

我试图按博客总数显示值A,B,C或D.但我收到错误 - 无法将关键字'total'解析为字段。有人建议正确的方法。谢谢

models.朋友

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.朋友

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')
            )
python django
1个回答
2
投票

你还必须使用Django F()Count()注释函数... 试试以下代码:

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__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(),
    )
)
© www.soinside.com 2019 - 2024. All rights reserved.