nkt
nkt

Reputation: 403

Reduce number of QuerySet for django project

I am making an Entity-Review-Vote kind of system where each entity will have some reviews, and each review will have some vote (up/down)

class Entity(models.Model):
    name = models.CharField()
    ...

class Review(models.Model):
    author = models.ForeignKey(user)
    entity = models.ForeignKey(Entity)
    ....

class Vote(models.Model):
    vote_user = models.ForeignKey(user)
    vote_review = models.ForeignKey(Review)
    vote_value = models.BooleanField() # True = Up

For each entity, I want to have a list of reviews, annotated with number of upvotes and downvotes for each review.

So far, my approach is to run 2 extra query for each review:

count_up = Vote.objects.filter(vote_review__id = X, vote_value = True)
count_down = Vote.objects.filter(vote_review__id = X, vote_value = False)

This returns correct result. However, the number of queries seem quite inefficient.

May I know if there is a better way to construct the queries? Or how to change the schema to better support this kind of operation?

Thanks

Upvotes: 1

Views: 384

Answers (1)

Sayse
Sayse

Reputation: 43300

If all you want is the count then you should just use count

Returns an integer representing the number of objects in the database matching the QuerySet. The count() method never raises exceptions.

count_up = Vote.objects.filter(vote_review__id = X, vote_value = True).Count()
count_down = Vote.objects.filter(vote_review__id = X, vote_value = False).Count()

This will modify the queries to just return the number of objects that the query creates and stops it from spending time returning the models.

Upvotes: 1

Related Questions