Django: queryset filter for *all* values from a ManyToManyField

Hi (sorry for my bad english :p)

Imagine these models :

class Fruit(models.Model): # ... class Basket(models.Model): fruits = models.ManyToManyField(Fruit)

Now I would like to retrieve Basket instances related to all fruits. The problem is that the code bellow returns Basket instances related to any fruits :

baskets = Basket.objects.filter(fruits__in=Fruit.objects.all()) # This doesn't work: baskets = Basket.objects.filter(fruits=Fruit.objects.all())

Any solution do resolve this problem ?

Thank you very much. :)

-------------Problems Reply------------

I don't have a dataset handy to test this, but I think it should work:


It annotates every basket object with the count of related fruits and filters out those baskets that have a fruit count that equals the total amount of fruits.

Note: you need Django 1.1 for this to work.

Category:python Views:10 Time:2009-09-21

Related post

  • Django queryset filter for blank FileField? 2011-01-23

    How do I perform a Django queryset filter looking for blank files in "FileField" fields? The field isn't null, it has a FileObject in it that doesn't have a file. --------------Solutions------------- I was having this issue too, and finally found the

  • use fuzzy matching in django queryset filter 2012-02-21

    Is there a way to use fuzzy matching in a django queryset filter? I'm looking for something along the lines of Object.objects.filter(fuzzymatch(namevariable)__gt=.9) or is there a way to use lambda functions, or something similar in django queries, a

  • Django Queryset Filter on an empty list 2011-04-22

    I'm building dynamic filters which I pass by GET to a queryset filter: for k, v in request.GET.iteritems(): kwargs[str(k)] = str(v) students = models.Student.objects.filter( **kwargs ) and it's working for almost all the queries I'm throwing at it. H

  • Django QuerySet filter method returns multiple entries for one record 2010-04-16

    Trying to retrieve blogs (see model description below) that contain entries satisfying some criteria: Blog.objects.filter(entries__title__contains='entry') The results is: [<Blog: blog1>, <Blog: blog1>] The same blog object is retrieved t

  • Django QuerySet filter + order_by + limit 2010-06-15

    So I have a Django app that processes test results, and I'm trying to find the median score for a certain assessment. I would think that this would work: e = Exam.objects.all() total = e.count() median = int(round(total / 2)) median_exam = Exam.objec

  • Django QuerySet filter in with a given sorted list 2013-01-05

    class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __unicod

  • How to filter a django queryset using an array on a field like SQL's "IN"? 2010-10-25

    I'd like to filter a django queryset using an array as a constraint on a field. AKA, my array, for example, a set of primary keys. I want to get only the objects that would be in that array, like the query in SQL would be SELECT * from table where id

  • Django model queryset filter as a function 2011-02-08

    I'm trying to create a custom function that I can place in a queryset "chain" that will apply a filter to the queryset. Like with normal Django queryset filters, it will take the queryset to the left of it and pass the resulting queryset to the right

  • How to filter a django queryset based on the number of many-to-many relationships? 2011-07-07

    I have the following situation: A person can belong to multiple organizations and an organization can have multiple members (Persons) class Person(models.Model): organizations = ManytoManyField(Organization) I want to classify the Organizations by nu

  • How do I do a not equal in Django queryset filtering? 2009-03-26

    In Django model QuerySets, I see that there is a __gt and __lt for comparitive values, but is there a __ne/!=/<> (not equals?) I want to filter out using a not equals: Example: Model: bool a; int x; I want results = Model.objects.exclude(a=true

  • How to compare value of 2 fields in Django QuerySet? 2009-04-27

    I have a django model like this: class Player(models.Model): name = models.CharField() batting = models.IntegerField() bowling = models.IntegerField() What would be the Django QuerySet equivalent of the following SQL? SELECT * FROM player WHERE batti

  • How do I create a Django queryset equivalent to a SQL query using the OR operator? 2009-05-05

    In Django, I know using filter with multiple arguments gets translated into SQL AND clauses. From the Django Book: You can pass multiple arguments into filter() to narrow down things further: >>> Publisher.objects.filter(country="U.S.A.", st

  • Django QuerySet equivalent for SQL's between and 2009-09-16

    Let's say I have the following table: Employee name start_date end_date John 2009-10-10 2009-12-31 Joe 2009-12-01 2010-05-10 I also have a curr_date = '2009-11-01'. If I want to get all employees where curr_date should be between an employee's start_

  • Django date filter by day of month 2009-11-03

    I need to write a query that returns all object less that or equal to a certain day of a certain month. The year is not important. It's easy enough to get an object by a particular day/month (assume now = posts = TodaysObjec

  • Matching blank entries in django queryset for optional field with corresponding ones in a required field 2010-04-08

    I have a django queryset in my views whose values I pack before passing to my template. There is a problem when the queryset returns none since associated values are not unpacked. the quersyet is called comments. Here is my def forums(reques

  • Difference between Django's filter() and get() methods 2010-07-11

    What is the difference between mymodel=model.objects.get(name='pol') and mymodel=model.objects.filter(name='pol') --------------Solutions------------- The Django QuerySet docs are very clear on this: get(**kwargs)¶ Returns the object matching the giv

  • What is a django QuerySet? 2011-01-13

    When i do this >>> b = Blog.objects.all() >>> b i get this >>>[<Blog: Blog Title>,<Blog: Blog Tile>] When i query what type b is, >>> type(b) i get this >>> <class 'django.db.models.query.Qu

  • Django objects.filter() values_list() vs python list comprehension for __in query 2011-01-27

    I have a quirk(?) with Django queryset filtering: ipdb> MagazineIssue.objects.filter(id__in=l_magazines.values_list('id')) Out[0]: [] or ipdb> MagazineIssue.objects.filter(id__in=[ for l_magazine in l_magazines]) Out[0]: [<Magaz

  • Limiting Memory Use in a *Large* Django QuerySet 2011-01-31

    I have a task which needs to be run on 'most' objects in my database once every some period of time (once a day, once a week, whatever). Basically this means that I have some query that looks like this running in it's own thread. for model_instance i

Copyright (C), All Rights Reserved.

processed in 0.103 (s). 11 q(s)