hmcclungiii
hmcclungiii

Reputation: 1805

How do I filter a Django Queryset by removing results in which another model has a ForeignKey relationship?

With the following models.py ...

from django.db import models

class Notebook(models.Model):
    name = models.CharField(max_length=255)
    
    
class Entry(models.Model):
    notebook = models.ForeignKey(Notebook, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)

How would I write a filter to only return Notebook that have no Entry?

Upvotes: 0

Views: 25

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

You can .filter(…) the Notebooks with:

Notebook.objects.filter(entry=None)

This works because Django makes a LEFT OUTER JOIN, and thus we only retain the records for which the entry primary key is NULL/None.

Upvotes: 1

Related Questions