Pittfall
Pittfall

Reputation: 2851

How can I use a different object manager for related models?

I have a couple of classes:

class Person(models.Model):
    address = models.ForeignKey(Address, on_delete=models.CASCADE)

class Address(LiveModel):
    address = models.CharField(max_length=512)

    some_manager = SomeManager()
    some_other_object_manager = OtherManager()

    class Meta:
        base_manager_name = 'some_other_object_manager'

Because I set some_manager, the default manager used is SomeManager which is good. BUT if I am querying a Person, I want it to use Address's OtherManager manager for querying and I thought that by setting base_manager_name, I would be able to achieve this (https://docs.djangoproject.com/en/2.2/topics/db/managers/#using-managers-for-related-object-access). Unfortunately this does not work. Any ideas? Particularly I am trying to achieve this in the admin, if that makes a difference.

Upvotes: 1

Views: 371

Answers (1)

Pittfall
Pittfall

Reputation: 2851

To clarify, this does work as intended. The issue here was in the detail. I was using the Django admin which does not query the related fields the way I expected. It actually uses the related fields default manager for the queryset. If you want to do what I am trying to do, this is a nice simple example: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/filter_fk_dropdown.html

Upvotes: 1

Related Questions