如何在django中用条件编写用于连接三个表的过滤器和顺序的查询

时间:2015-02-05 05:37:47

标签: python django

我有三种模式:

class Category(models.Model):
    category_name = models.CharField(max_length=128, unique=True)
    category_alias = models.CharField(max_length=128, unique=True)
    category_desc = models.TextField()

class Question(models.Model):
    user = models.ForeignKey(User)
    category = models.ForeignKey(Category)
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(auto_now=True)
    is_approved = models.BooleanField(default=0)

class Answer(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question)
    answer = models.TextField()
    is_approved = models.BooleanField(default=0)

class Rating(models.Model):
    user = models.ForeignKey(User)
    answer = models.ForeignKey(Answer)
    rating = models.BooleanField(default=0)

我需要一个查询,它会找到最喜欢的答案(答案最多的评分)及其特定类别的问题和评级。这意味着如果答案2具有最多的评级,那么我将得到该答案的对象以及任何特定类别的相关问题和评级。

1 个答案:

答案 0 :(得分:1)

class Rating(models.Model):
    user = models.ForeignKey(User)
    answer = models.ForeignKey(Answer)
    rating = models.BooleanField(default=0, related_name='rating')


answers = Answer.objects.filter(question__category__id=category_id).annotate(
    rating_sum=Count(rating__rating)).order_by('-rating_sum')

您应该使用'annotate'方法来计算正面标记并按此字段排列答案。