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

240
Views
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 answers
Answer question

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 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!