我有这个模特:
class Question(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=50, verbose_name='Titolo')
text = models.TextField(verbose_name='Testo')
category = TreeForeignKey(CoursesCategory, verbose_name='Categoria')
created_at = models.DateTimeField(auto_now_add=True)
我在另一个应用程序中有另一个模型:
class Like(models.Model):
user = models.ForeignKey(User)
value = models.IntegerField(verbose_name='Voto')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_pk = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_pk')
现在,我应该在问题视图中查询问题查询集,以及模型类似的相对值。
我正在尝试使用此方法
def get_queryset(self):
questions = Question.objects.all()
questions = questions.annotate(ranking_vote=Coalesce(Sum(...), 0)).order_by('-ranking_vote')
但我无法弄清楚解决方案是什么。
你能帮助我吗?答案 0 :(得分:0)
class Like(models.Model):
user = models.ForeignKey(User)
question = models.ForeignKey(Question) # New field
value = models.IntegerField(verbose_name='Voto')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_pk = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_pk')
在此之后,您可以在问题对象上使用:like_set
。
q.like_set.count() # return like number link to this question object
关于您的要求,您可以这样做:
from django.db.models import Count
questions = Question.objects.annotate(num_like=Count('like')).order_by('-num_like')