Search code examples
djangodjango-taggit

Get objects for which a type of foreign key exists


I'm using django-taggit to create an app that stores not only to-do items but also informational items. Both a to-do items and informational items can be tagged.

When I pull a list of tags for to-do items, I run the following query:

action_tags = Tag.objects.order_by('name').filter(action__complete=False).annotate(action_count=Count('action'))

This gives me the name of all tags for which there are incomplete to-dos. It also gives me the count of incomplete to-dos.

For the informational items, there is no field for "complete"; information items just "are". So I want to write a query that pulls all the tags for which there is at least one informational item. How might that be written?


Solution

  • I think this is the way, assuming info_item is the foreign key you want to verify exists:

    tags = Tag.objects.filter(
        info_item__isnull=False
    ).order_by(
        'name'
    ).annotate(
        info_item_count=Count('info_item')
    )