Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: get unique object list from QuerySet

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 
like image 542
rolling stone Avatar asked Sep 28 '11 23:09

rolling stone


People also ask

How to get unique values from QuerySet in django?

If you want to get distinct objects, instead of values, then remove flat=True from the above query, and use values() instead of values_list(). In the above code, we add distinct() at the end of queryset to get distinct values.

How does Django get unique data?

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values() .

What is QuerySet in django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

How to save data in models in django?

Creating objectsTo create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.


1 Answers

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() 
like image 144
John Keyes Avatar answered Oct 19 '22 14:10

John Keyes