skip to Main Content

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?

2

Answers


  1. 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)
    
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search