Reverse filtering via ManytoManyField

2010-01-09 Thread janedenone
I defined two models (Tag and Page), where the Page model links to the
Tag model:

tags = models.ManyToManyField(Tag, blank=True)

For a single tag, I can refer to the pages linked to that tag like so:

for page in tag.page_set:
   ...

results = tag.page_set.count()

But I cannot find a way to obtain a list of tags where each tag is
linked to at least one page. My attempt

tags = Tag.objects.filter(page_set__count__gt=0)

results in an error: Django complains that the field 'page_set' is
unknown. Why can I use page_set as a 'virtual' tag property (even
though this set is not defined in the model), and how can I refer to
the page_set in a query?

Many thanks,
Jan
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Reverse filtering via ManytoManyField

2010-01-11 Thread janedenone
Solved (in Django 1.1):

tags = Tag.objects.annotate(num_pages=Count('page')).filter
(num_pages__gt=0)

On 9 Jan., 19:50, janedenone  wrote:
> I defined two models (Tag and Page), where the Page model links to the
> Tag model:
>
> tags = models.ManyToManyField(Tag, blank=True)
>
> For a single tag, I can refer to the pages linked to that tag like so:
>
> for page in tag.page_set:
>    ...
>
> results = tag.page_set.count()
>
> But I cannot find a way to obtain a list of tags where each tag is
> linked to at least one page. My attempt
>
> tags = Tag.objects.filter(page_set__count__gt=0)
>
> results in an error: Django complains that the field 'page_set' is
> unknown. Why can I use page_set as a 'virtual' tag property (even
> though this set is not defined in the model), and how can I refer to
> the page_set in a query?
>
> Many thanks,
> Jan
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.