我正在尝试根据博主的总数显示值 A、B、C 或 D。但我收到错误 - 无法将关键字“总计”解析为字段。有人可以建议正确的方法吗?谢谢
模型.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)
View .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')
)
请您参考如下方法:
您还必须使用 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__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(),
)
)
