djangogoogle-app-enginedjango-adminapp-engine-patch

Optimizing ModelChoiceField query in django Admin (AppEngine)


I have two models: Activity and Place. The Activity model has a ReferenceProperty to the Place model.

This was working fine until the Place table started growing and now when trying to edit an Activity via django admin I get a memory error from Google (it doesn't happen if I remove that field from the Activity admin's fieldsets)

The widget used to edit the RefrenceProperty uses Place.all() to get the possible values. As both Activity and Place are sharded by a city property I would like to optimize the widget's choice query from Place.all() to just the relevant places, for example Place.all().filter("city =", )

I couldn't find a way to override the query in the docs and I was wondering if the above is even possible? and if so, how?


Solution

  • Managed to optimize the query by overriding the admin form:

    class ActivityAdminForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(ActivityAdminForm, self).__init__(*args, **kwargs)        
            self.fields['place'].queryset = <... my query ...>
    
    
    class ActivityAdmin(admin.ModelAdmin):
        form = ActivityAdminForm