Django: get unique object list from QuerySet?

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

Up vote 1 down vote favorite share g+ share fb share tw.

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. Thanks. Django django-queryset django-queries link|improve this question asked Sep 28 '11 at 23:05rolling stone2,330110 96% accept rate.

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().

1 thanks. The real original query was actually much more complicated than user=request. User so ended up going with the first part of your answer.

– rolling stone Sep 29 '11 at 17:56.

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).

1 thanks (the cleaned up query above/below has the correct syntax). – rolling stone Sep 29 '11 at 17:57.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions