I have the following (simplified) models in my Django app:
class Color(models.Model):
name = models.CharField(max_length=10)
class Item(models.Model):
name = models.CharField(max_length=200)
color = models.ForeignKey(Color, blank=True, null=True)
class Favorite(models.Model):
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
I’m currently getting all the items I need using the following query:
favorites = Favorite.objects.filter(user=request.user)
How can I get all the distinct colors for the items in that QuerySet?
I need the a list of the actual color objects, not just the color ids, which I can get using
favorites.values_list('item__color').distinct
If I understand you correctly, the following should do the trick:
There has to be a cleaner way than that though.
Edit: A much cleaner solution: