问题
I'm using django 1.9 and django.contrib.gis with an Area model that has a huge gis MultiPolygonField:
# models.py
from django.contrib.gis.db import models as gis_models
class Area(gis_models.Model):
area_color = gis_models.IntegerField()
mpoly = gis_models.MultiPolygonField(srid=4326)
class Meta:
verbose_name = 'Area'
verbose_name_plural = 'Areas'
I have the associated AreaAdmin class to manage the Areas inside django admin:
# admin.py
from django.contrib.gis import admin as gis_admin
class AreaAdmin(gis_admin.OSMGeoAdmin):
map_width = 800
map_height = 600
modifiable = False
list_display = ['area_color', ]
exclude = ['mpoly', ]
gis_admin.site.register(Area, AreaAdmin)
The problem is that even though I'm using list_display that doesn't contain mpoly and the exclude attribute to prevent it's display in the form view , when displaying the list view, it still fetches all the fields from the database and loads it into memory. Because the mpoly is so huge, I'm having random errors (segfault, processed killed, ...) and the list display takes many minutes to display some simple integer fields...
Is there any way to tell django not to load the mpoly into memory, to ignore it completely in it's database query so it will load fast ? I haven't found anything in the documentation aside from exclude to remotely achieve this. I'm asking here in case I'm missing something.
Thank you for your assistance.
回答1:
You can try to override the get_queryset method used in generating the list view for AreaAdmin.
class AreaAdmin(gis_admin.OSMGeoAdmin):
def get_queryset(self, request):
qs = super(AreaAdmin, self).get_queryset(request)
# tell Django to not retrieve mpoly field from DB
qs = qs.defer('mpoly')
return qs
For more information on defer see https://docs.djangoproject.com/es/1.9/ref/models/querysets/#defer
来源:https://stackoverflow.com/questions/34774028/how-to-ignore-loading-huge-fields-in-django-admin-list-display