Search code examples
djangodjango-modelsdjango-database

Django different model manager on foreign key


I have model User. There are two managers, UserManager that filters query set by is_active, and AllUserManager. Default manager is set to be UserManager.

User has foreign key to another model, named Address, having related_name='users'.

Problem is next. When User is_active is False, Address does not display inactive User in users collection.

Is it possible somehow to set AllUserManager to be default manager on the fly for some FK? I want to be able to list all users in address, regardless of their activity.


Solution

  • You can specify which manager to use in queries. If all_users = AllUserManager() then:

    # address is instance of Address
    address.users(manager='all_users').all()
    

    Also, if all_users is default manager, you can set use_for_related_fields = True on AllUserManager.