Limiting Records in Django Admin

October 2, 2010

I had a situation where the Django admin would be deployed on multiple sites, all using the same source code. Each site had a unique settings.py and the SITE_ID was different for each. Each site had an admin site that was limited to that particular site's data.

models.py

Each model object had a foreign key on for the site and an on_site manager which returned rows only for the current site.

from django.db import models
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager

class AudioEvent(models.Model):
    #...
    site = models.ForeignKey(Site,default=Site.objects.get_current().id,editable=False)
    objects = models.Manager()
    on_site = CurrentSiteManager()

admin.py

The admin configuration used a common superclass and overrode the queryset method to limit the results to just the ones for this site.

from django.contrib import admin
from mysite.audio.models import AudioEvent
from mysite.admin import SiteOnlyAdmin

class AudioEventAdmin(SiteOnlyAdmin):
    def queryset(self,request):
        return AudioEvent.on_site.all()

admin.site.register(AudioEvent, AudioEventAdmin)

Foreign Keys

To limit the droplists to data only from this site, the superclass (SiteOnlyAdmin) defined the foreignkey_filters attribute and inherited from the ForeignKeyFilter class.

class ForeignKeyFilter(object):
    def formfield_for_dbfield(self, db_field, **kwargs):
        # Only show the foreign key objects from the rendered filter.
        filters = getattr(self, 'foreignkey_filters', None)

        if filters and db_field.name in filters:
            kwargs['queryset'] = filters[db_field.name](Site.objects.get_current())

        return admin.ModelAdmin.formfield_for_dbfield(self, db_field, **kwargs)

class SiteOnlyAdmin(ForeignKeyFilter, admin.ModelAdmin):
    foreignkey_filters = {
                          'site' : lambda site : Site.objects.filter(name=site.name)
                         }

Tags: django admin limit data