3

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
EnterSB
  • 984
  • 2
  • 10
  • 27

1 Answers1

8

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.

chiseledCoder
  • 369
  • 6
  • 16
vsd
  • 1,473
  • 13
  • 11
  • 1
    use_for_related_fields is deprecated, see: https://docs.djangoproject.com/en/dev/releases/1.10/#manager-use-for-related-fields-and-inheritance-changes – rrmoelker Aug 19 '19 at 14:48
  • But what about when its not a queryset but just an instance. eg: `phone.user` and the phone belongs to a user which is not included in the default manager for the related fields? – Neeraj Kumar Feb 12 '22 at 07:08