[Answer]-Queryset only get one (any) record for each foreign key

1๐Ÿ‘

I simply need to end up with a list of Cars wherein the
Manufacturer is unique.

How about using distinct:

cars = Car.objects.order_by('manf').distinct('manf')

Since the above is only supported on PostgreSQL, you have to work around it:

m = Manufacturer.objects.all()

cars = []
for i in m:
    if Car.objects.filter(manf=i).exists():
       cars.append(Car.objects.filter(manf=i).order_by('?')[1])

This will give you one random car for each manufacturer.

๐Ÿ‘คBurhan Khalid

0๐Ÿ‘

I am not sure how we can do it with orm. Can tell how we can achieve it through direct sql:

from django.db import connection
cursor = connection.cursor()

cursor.execute("select c.model from myapp_car c, myapp_manufacturer m where m.origin='USA' and m.id=c.manf_id group by m.id")
๐Ÿ‘คAkshar Raaj

Leave a comment