How about using filter() before annotate()

Topic.objects.filter(subtopics__trashed_at__isnull=true,
subtopics__complete_at__isnull=True).annotate(Count('subtopics'))

That filters out the records you don't want and then performs the
annotation on the remaining set.

On Sep 26, 6:04 am, "oliver.andrich" <oliver.andr...@gmail.com> wrote:
> Hi,
>
> is it possible to constrain a Count aggregate by adding some extra
> filters?
>
> I have a model which has a self referentiell foreign key.
>
> class Topic(models.Model):
>     ...
>     topic                   = models.ForeignKey('self',
> related_name='subtopics', null=True, blank=True)
>     ...
>
> Now I would like to select a list of Topic instances which is
> annotated with the count of subtopics. This works like a charm with
> the following statement.
>
> Topic.objects.all().annotate(Count('subtopics'))
>
> But can I constrain the subtopics which are counted? Topics have an
> attribute trashed_at and complete_at. I only want the count the
> subtopics, where these attributes are null.
>
> Currently, I do this with extra and a custom SQL query. But the source
> of the aggregates suggest I can add a some extra constraints.
>
> Can anybody supply a working example?
>
> Best regards,
> Oliver
--~--~---------~--~----~------------~-------~--~----~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to