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 Bars grouped by Foo. This is accomplished by:
Foo.objects.annotate(num_bars=Count('bar'))
Which gives me back a QuerySet of Foos annotated with the number of Bars.
Now I would like to exclude some Bars based on their state. Let's say the states 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 Bars grouped by Foo. This is accomplished by:
Foo.objects.annotate(num_bars=Count('bar'))
Which gives me back a QuerySet of Foos annotated with the number of Bars.
Now I would like to exclude some Bars based on their state. Let's say the states 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