Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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
    )
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

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")
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda