How to ignore loading huge fields in django admin list_display?

时光怂恿深爱的人放手 提交于 2020-01-24 09:25:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!