Question

I have the following models:

from django.db import models


class Tag(models.Model):
    name = models.CharField('title', max_length=100)


class Post(models.Model):
    title = models.CharField('title', max_length=100)
    body = models.TextField('body')
    tags = models.ManyToManyField(Tag)

How can I build a QuerySet that selects all tags that are not related to any blog post?

Was it helpful?

Solution

You can do:

tags = Tag.objects.filter(post__isnull=True)

You can read more on lookups that span multivalued relationships here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top