Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda