How to use custom manager with related objects?

For completeness of the topic, Django 1.7 (finally) supports using a custom reverse manager, so you can do something like that (just copying from the django docs): from django.db import models class Entry(models.Model): objects = models.Manager() # Default Manager entries = EntryManager() # Custom Manager b = Blog.objects.get(id=1) b.entry_set(manager=”entries”).all()

Django custom managers – how do I return only objects created by the logged-in user?

One way to handle this would be to create a new method instead of redefining get_query_set. Something along the lines of: class UserContactManager(models.Manager): def for_user(self, user): return super(UserContactManager, self).get_query_set().filter(creator=user) class UserContact(models.Model): […] objects = UserContactManager() This allows your view to look like this: contacts = Contact.objects.for_user(request.user) This should help keep your view simple, and because … Read more

How to Unit test with different settings in Django?

EDIT: This answer applies if you want to change settings for a small number of specific tests. Since Django 1.4, there are ways to override settings during tests: https://docs.djangoproject.com/en/stable/topics/testing/tools/#overriding-settings TestCase will have a self.settings context manager, and there will also be an @override_settings decorator that can be applied to either a test method or a … Read more

Custom QuerySet and Manager without breaking DRY?

The Django 1.7 released a new and simple way to create combined queryset and model manager: class InquiryQuerySet(models.QuerySet): def for_user(self, user): return self.filter( Q(assigned_to_user=user) | Q(assigned_to_group__in=user.groups.all()) ) class Inquiry(models.Model): objects = InqueryQuerySet.as_manager() See Creating Manager with QuerySet methods for more details.