Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
order_by creates duplicate entries

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

models:

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.

Update

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
    )
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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")
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!