简体   繁体   中英

Django 1.6 ORM count subset of related items

I have these models

class BlogEntry(models.Model):
    tags = models.ManyToMany(Tag, ...)
    ...

class Tag(models.Model):
    ...

and a subset of tags:

tag_list = list(*some tag objects*)   # can refactor to queryset

I need to get the number of tags for each BlogEntry that is in my tags list, so something like this:

# Non-working code ahead
BlogEntry.objects.annotate(match=Count(tags__in=tag_list))

I've got this code to run just fine

# working code ahead
for entry in BlogEntry.objects.all():
        match = len(set(entry.tags.all()).intersection(tag_list))

But I feel like doing the counting and intersecting in python rather than in the database could pose a performance issue down the road.

See the documentation on the order of annotate() and filter() clauses .

As that section says, if you filter before you annotate, then the annotation will only include elements matched by the filter. So:

BlogEntry.objects.filter(tags__in=tag_list).annotate(match=Count(tags))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM