[Django]-Django: get unique object list from QuerySet

49👍

If I understand you correctly, the following should do the trick:

favorites = Favorite.objects.filter(user=request.user)
color_ids = favorites.values_list('item__color', flat=True).distinct()
colors = Color.objects.filter(id__in=color_ids)

There has to be a cleaner way than that though.

Edit: A much cleaner solution:

colors = Color.objects.filter(item__favorite__user=request.user).distinct()

8👍

Can you do:

Color.objects.filter(item__favorite__user = request.user).distinct()

You might have to set some related_names on your foreign keys if these aren’t the defaults (I can never remember the defaults).

👤Dave

8👍

Can you do:

favorites = Favorite.objects.filter(user=request.user).distinct('item__color')
👤ARK

0👍

The is values_list(*fields, flat=False, named=False) method, so run it on your objects, for example:

user.groups.values_list('name', flat=True)
👤Alex

Leave a comment