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

237
Vistas
Get queryset of objects that are unique based on a field - Django

I have a large inventory of vehicles, and there are a lot of duplicates that are only unique by a stock number. I am trying to query for a list of all vehicles, but only want one vehicle for each model number, ignoring it's stock number field.

V1.stock_no = 15393

V2.stock_no = 15394

V1.model_no = 98874

V2.model_no = 98874

So when doing a query in Django, I only want one instance of each object with that model no. I read this Stack Overflow question Select DISTINCT individual columns in django?, but

q = ProductOrder.objects.values('Category').distinct()

just returns a distinct list of model numbers, and not the object instance, and

Productorder.objects.all().distinct('category')

made available since Django 1.4, only works with PostgreSQL, and not SQLite3.

Is there any way to do this with SQLite, without having some contrived for loop to get it done ?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

This is one potential solution

q = ProductOrder.objects.filter(
    id__in=ProductOrder.objects.values('Category')
                               .distinct()
                               .values_list('id', flat=True))

Edit: alternatively, you can try

q1 = ProductOrder.objects.values('Category')
                               .distinct()
                               .annotate(x=Max('id'))
q2 = ProductOrder.objects.filter(
    id__in=[i["x"] for i in q1])

I realize this is not ideal however due to having to loop.

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