2👍
✅
Create a custom manager:
class ContainerManager(models.Manager):
def get_query_set(self, *args, **kwargs):
qs = super(ContainerManager, self).get_query_set(*args, **kwargs)
annotations = {'tag_count':models.Count('tag'), 'com_count':models.Count('com')}
return qs.annotate(**annotations)
class Container(models.Model):
...
objects = ContainerManager()
Then, Container
queries will always include tag_count
and com_count
attributes. You’ll probably need to modify the annotations, since I don’t have a copy of your model to refer to; I just guessed on the field names.
UPDATE:
So after gaining a better understanding of your models, annotations won’t work for what you’re looking for. Really the only to get counts for how many Container
s have kind
s of ‘tag’ or ‘com’ is:
tag_count = Container.objects.filter(kind='tag').count()
com_count = Container.objects.filter(kind='com').count()
Annotations won’t give you that information. I think it’s possible to write your own aggregates and annotations, so that might be a possible solution. However, I’ve never done that myself, so I can’t really give you any guidance there. You’re probably stuck with using straight SQL.
Source:stackexchange.com