I have two models
class Foo(models.Model):
pass
class Bar(models.Model):
foo = models.ForeignKey(Foo)
state = models.CharField()
I would like to count all of the Bar
s grouped by Foo
. This is accomplished by:
Foo.objects.annotate(num_bars=Count('bar'))
Which gives me back a QuerySet of Foo
s annotated with the number of Bar
s.
Now I would like to exclude some Bar
s based on their state
. Let's say the state
s are all either 'A'
or 'B'
and I don't want to count the 'B'
s. I tried the following:
Foo.objects.exclude(bar__state='B').annotate(num_bars=Count('bar'))
But this returns a count of zero for any Foo
where there is at least one Bar
with state
'B'. I thought it would have returned the same as:
Foo.objects.filter(bar__state='A').annotate(num_bars=Count('bar'))
Which, in this case also excludes all 'B'
. Unfortunately, the method using filter
isn't so good because there are actually several states and I only want to exclude one (and in principle, there could be more in the future).
So, what am I doing wrong? What is the right way to exclude before doing an annotation?
I have two models
class Foo(models.Model):
pass
class Bar(models.Model):
foo = models.ForeignKey(Foo)
state = models.CharField()
I would like to count all of the Bar
s grouped by Foo
. This is accomplished by:
Foo.objects.annotate(num_bars=Count('bar'))
Which gives me back a QuerySet of Foo
s annotated with the number of Bar
s.
Now I would like to exclude some Bar
s based on their state
. Let's say the state
s are all either 'A'
or 'B'
and I don't want to count the 'B'
s. I tried the following:
Foo.objects.exclude(bar__state='B').annotate(num_bars=Count('bar'))
But this returns a count of zero for any Foo
where there is at least one Bar
with state
'B'. I thought it would have returned the same as:
Foo.objects.filter(bar__state='A').annotate(num_bars=Count('bar'))
Which, in this case also excludes all 'B'
. Unfortunately, the method using filter
isn't so good because there are actually several states and I only want to exclude one (and in principle, there could be more in the future).
So, what am I doing wrong? What is the right way to exclude before doing an annotation?
0 commentaires:
Enregistrer un commentaire