Home > Software engineering >  How to filter records that doesn't have a record in a related table?
How to filter records that doesn't have a record in a related table?

Time:12-15

Consider the two models below:

from django.db import models


class Author(models.Model):    
    name = models.CharField(max_length=255)

    
class Book(models.Model):
    author = models.ForeignKey(Author, models.CASCADE, related_name="books")

how to get only authors that does not have books?

CodePudding user response:

You could do something like this: fetch all the authors of books, and then fetch all the authors that you didn't retrieve in the first query (meaning they have no books).

Untested code:


# fetch all the author ids that have books
authors_with_books = Book.objects.distinct('author').values_list('author_id', flat=True)

# fetch all the authors that have no books
authors_with_no_books = Author.objects.exclude(id__in=authors_with_books)

CodePudding user response:

You can use isnull or just pass None to the related_name to perform this filter

Author.objects.filter(books__isnull=True)
Author.objects.filter(books=None)
  • Related