I had a similar problem, and just used custom SQL. It's easy:

        from django.db import connection
        cursor = connection.cursor()
        cursor.execute("""
                SELECT cars_model.id, cars_model.opis,
                cars_znamka.id, cars_znamka.opis,
                COUNT(*)
                FROM cars_model, cars_vozilo, cars_znamka
                WHERE cars_model.id=cars_vozilo.model_id
                AND cars_znamka.id = cars_model.znamka_id
                GROUP BY cars_model.id, cars_model.opis, cars_znamka.id, 
cars_znamka.opis
                HAVING COUNT(*)>0
        """)
        result_list = []
        for row in cursor.fetchall():
                # create the dictionary object, that you'll pass to your 
template.
                 dict_obj = {
                        "id" : row[0],
                        "opis" : "%s %s" % (row[3], row[1]),
                        "cars_count":row[4]
                 }
                 result_list.append(dict_obj)

        # template expects "model_list"
        model_list = result_list


Hope this helps,

Carlos

On 7/16/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> Hi.
>
> This is probably trivial, but I've not managed to find the solution.
> How do I filter objects based on the count of a ManyToManyField?
>
> My example:
>
> I have two classes -- Blog and Submission:
>
> class Blog( models.Model ):
>     entries = models.ManyToManyField( Submission )
>
> class Submission( models.Model ):
>   [... whatever ]
>
> I want to fetch a list of all Blog instances which have at least one
> Submission , i.e. entries.count() > 0. Changing the model is not an
> option.
>
> I've been trying all kinds of permutations of filter, entries, count,
> gt, etc, such as:
> Blog.objects.filter(entries__count__gt = 0)
>
> No luck so far.
>
> Can somebody please help me?
>
> Thanks,
>     Daniel
>
>
> >
>


-- 
Carlos Yoder
http://carlitosyoder.blogspot.com

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to