My main question is: is there a way to change the behavior of a linked search, for example MyModel.objects.filter(relationship__field="value")?
Consider this setting. I have a one-to-many relationship with a custom dispatcher that filters books withactive=False
from django.db import models
class ActiveOnly(models.Manager):
use_for_related_fields = True
def get_queryset(self):
return super(ActiveOnly, self).get_queryset().filter(active=True)
class Author(models.Model):
name = models.TextField()
class Book(models.Model):
active = models.BooleanField()
author = models.ForeignKey(Author, related_name="books")
title = models.TextField()
objects = ActiveOnly()
And create some data:
jim = Author.objects.create(name="Jim")
ulysses = Book.objects.create(title="Ulysses", author=jim, active=True)
finnegans = Book.objects.create(title="Finnegan Wake", author=jim, active=False)
bill = Author.objects.create(name="Bill")
hamlet = Book.objects.create(title="Hamlet", author=bill, active=False)
In fact, I never want to deal with inactive books. Here are some queries to test different scenarios.
>>> Book.objects.all().count()
1
>>> jim.books.all()
1
>>> Author.objects.filter(books__title="Hamlet").first().name
u'Bill'
Is there any way to change the search behavior books__*to enable an additional filter in active?
source
share