nobe4
nobe4

Reputation: 2842

Django override manager in admin

I have a model which use a custom manager:

class ProjectManager(models.Manager):
    def get_queryset(self):
        return super(ProjectManager, self).get_queryset() \
            .exclude(archived_date__isnull=False)


class Project(models.Model):
    objects = ProjectManager()
    archived_date = models.DateTimeField(null=True, blank=True)

But I haven't found a way to display all Projects in the admin.

My admin is defined as follow:

class ProjectAdmin(admin.ModelAdmin):
    model = Project

I tried to use the get_queryset in the ProjectAdmin class, but I could not figure out a way to get back all projects.

Do you know a way to do it?

Upvotes: 0

Views: 1699

Answers (1)

justdavey
justdavey

Reputation: 236

You will need to set the manager as default manager.

objects = ProjectManager() # The default manager.

Source: https://docs.djangoproject.com/en/4.1/topics/db/managers/#modifying-a-manager-s-initial-queryset

EDIT:

This might not be the best solution, but this will work.

models.py:

class Project(models.Model):
    objects_unfiltered = models.Manager()

admin.py

class ProjectAdmin(admin.ModelAdmin):
    model = Project

    def get_queryset(self, request):
        return self.model.objects_unfiltered.all()

admin.site.register(Project, ProjectAdmin)

Upvotes: 5

Related Questions