Menu

1 / 2

Stop Repeating .filter(is_active=True) Everywhere

DEV Community: python·Anas Issath·about 20 hours ago
#H83qZsJq
#devtopython#devto#dev#queryset#objects
Reading 0:00
15s threshold

Custom managers and querysets: how to name your query logic once, reuse it everywhere, and chain it like Django's built-in methods.

Look through almost any Django codebase and you'll find the same filter written over and over. Post.objects.filter(status="published") in the list view, again in the API, again in the sidebar, again in the sitemap. Or User.objects.filter(is_active=True, is_deleted=False) scattered across forty files.

It works, until someone adds a new rule ( "also exclude banned users" ). Now you have to find and update all forty places, you'll miss three of them, and there's a bug in production.

This is exactly the problem custom managers and querysets solve, and it's one of the most underused features in Django. It lets you take a piece of query logic ("the published posts," "the active users"), give it a name, define it once, and reuse it everywhere as Post.objects.published() . The query lives in one place.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.