Django: get unique object list from QuerySet
django queryset get field value
distinct in django filter
django annotate distinct
django get list of values from queryset
django q object
django filter in list
django iterate over 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
I need the a list of the actual color objects, not just the color ids, which I can get using
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()
You want to find users whose names have not been repeated. You can do this like this. distinct = User.objects.values( 'first_name' ).annotate( One more thing: before Django 1.6, there was a bug with calling values_list() on a queryset ordered by an extra column. Use this : Use this : values = queryset . values ( 'ordering' , 'label' ) labels = [ value [ 'label' ] for value in values ]
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).
If you generate a pickle using Django version N, there is no guarantee that pickle Annotates each object in the QuerySet with the provided list of query expressions. See the note in distinct() for an explanation of how related model ordering get_blank_or_404.diff (2.0 KB) - added by SuperJared 13 years ago. Diff for django/shortcuts/ init .py modeltests.get_object_or_404.models.py.diff ( 831 bytes ) - added by SuperJared 13 years ago .
Can you do:
favorites = Favorite.objects.filter(user=request.user).distinct('item__color')
Pull Requests: How to create a pull request Article.objects.filter(product_number=99668).values_list('product_number', flat=True).distinct() QuerySet.distinct. django-users mailing list Search for information in the archives of the django-users mailing list, or post a question. #django IRC channel Ask a question in the #django IRC channel, or search the IRC logs to see if it’s been asked before. Ticket tracker Report bugs with Django or Django documentation in our ticket tracker. Download:
values_list(*fields, flat=False, named=False) method, so run it on your objects, for example:
Understanding QuerySets is vital to getting good performance with simple code. with unique or db_index when using get() to retrieve individual objects. a dict or list of values, and don't need ORM model objects, make appropriate usage of I want to create a unique dict of all the Client objects in the query set so: Projects Queryset: - Project1.client = <Client: 1> - Project2.client = <Client: 1> - Project3.client = <Client: 2> - Project4.client = <Client: 2> - Project5.client = <Client: 3> class Project(models.Model): client = models.ForeignKey(Client, blank=True, null=True)
Note that you must save an object before it can be assigned to a foreign key relationship. <QuerySet [<Article: This is a test>]> # Find all Articles for any Reporter whose Article.objects.filter(reporter__in=[r,r2]).distinct() <QuerySet [<Article: John's second You can also use a queryset instead of a literal list of instances:. Using a unique slug may serve the same purpose, but this scheme allows you to have non-unique slugs. get_object(queryset=None)¶ Returns the single object that this view will display. If queryset is provided, that queryset will be used as the source of objects; otherwise, get_queryset() will be used.
distinct() - Returns a new QuerySet that uses SELECT DISTINCT in its SQL query. as Blog.objects.all() don't introduce the possibility of duplicate result rows. spans multiple tables, it's possible to get duplicate results when a QuerySet is bytearray ❘ BaseUserManager ❘ Page ❘ unicode ❘ list ❘ Paginator ❘ tuple ❘ str class Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True) [source] ¶ Paginator.object_list¶ Required. A list, tuple, QuerySet, or other sliceable object with a count() or __len__() method. For consistent pagination, QuerySet s should be ordered, e.g. with an order_by() clause or with a default ordering on the model.
For example, I want unique writter : Books.objects.filter(created__year=2012).order_by('writter').values('writter').distinct() But, how to get unique A QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the…
- +1 thanks. the real original query was actually much more complicated than
user=request.userso ended up going with the first part of your answer.
- +1 thanks (the cleaned up query above/below has the correct syntax).