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 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.
One way to get the list of distinct column names from the database is to use distinct() in conjunction with values() .
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With