简体   繁体   中英

How to write query for joining three tables with filter and order by condition in django

I have three model:

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)

I need a query which will find most liked answer(Answer which have most ratings) with its question and rating for a particular category. This mean if answer 2 have most ratings therefore i will get object for that answer with related question and ratings for any particular category.

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')

You should use 'annotate' method to count positive marks and arrange answers by this field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM