I have 4 model classes: User, Stack, Article and Rating. Users can create stacks, add articles, put them on a stack, rate the articles and share the stacks. I want to get a QuerySet of all articles of a specific stack (got by pk) and ordered by the current users rating. My query leads to duplicate entries in my QuerySet if the stack was shared and an article was rated by another user, so that there exists a rating object for an article twice:
qs = stack.article_set.all().order_by("ratings__rating", "-pk")
class Rating(models.Model):
article = models.ForeignKey(
Article,
on_delete=models.CASCADE,
related_name='ratings'
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='ratings'
)
rating = models.IntegerField()
class Stack(models.Model):
title = models.CharField(null=True, max_length=100)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Article(models.Model):
stack = models.ForeignKey(Stack, null=True, blank=True, on_delete=models.CASCADE)
text = models.TextField(null=True, blank=True)
How can I get the ordered QuerySet without the duplicates, just ordered by the request.user ratings.
What I do for now is to query twice. One time to get the already rated article objects ordered by the rating and a second time to get the currently not rated article objects unsorted.
context['rated_articles'] = deck.article_set.filter(
ratings__user__exact=self.request.user
).order_by("ratings__rating", "-pk")
context['not_rated_articles'] = deck.article_set.all().exclude(
ratings__user__exact=self.request.user
)
You should be able to filter the article set before you order it, based on the stacks owner
user = stack.owner
stack.article_set.filter(rating__user__exact=user).order_by("ratings__rating", "-pk")