多选择字段M2M的Django Admin list_per_page

时间:2019-02-22 11:08:16

标签: django pagination many-to-many multichoiceitems

我有一个m2m关系设置,它可以在管理员端运行。但是,它列出了所有60,000条记录(应有的记录),以便在加载时更有效地工作,如何限制返回的记录数。我已经研究过将list_per_page选项添加到admin.py中,但这似乎适用于对象列表,我需要在multiselectfield中添加它。

有什么想法吗?

# models.py

class Sample(models.Model):
    sample_id = models.AutoField(primary_key=True)
    area_easting = models.IntegerField(choices = EASTING_CHOICES)
    area_northing = models.IntegerField(choices = NORTHING_CHOICES)
    context_number = models.IntegerField()
    sample_number = models.IntegerField()
    sample_type = models.CharField(max_length=200, default='', blank=True, null=True, choices = MATERIALS)
    weight = models.DecimalField(max_digits=6, decimal_places=2)
    description = models.CharField(max_length=500, default='', blank=True, null=True)
    recovery_method = models.CharField(max_length=200, default='', blank=True, null=True, choices = RECOVERY_METHODS)
    taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='taken_by', on_delete = models.PROTECT, related_name='depotsample_taken_by')
    comments = models.CharField(max_length=1000, default='', blank=True, null=True)

    def __str__(self):
        return str(self.sample_number)


    class Meta:
        db_table = 'kap\".\"sample'
        #ordering = ["sample_id"]
        managed = True
        #verbose_name_plural = "samples"

class Container(models.Model):
    container_id = models.AutoField(primary_key=True)
    container_name = models.CharField(max_length=50, blank=True, null=True)
    container_type = models.CharField(max_length=50, blank=True, null=True)
    location_id = models.ForeignKey(Location, db_column='location_id', on_delete = models.PROTECT)

    samples = models.ManyToManyField('Sample')
    icon_desc = models.ForeignKey(Icon, db_column='icon_desc', null=True, blank=True, default='Box',on_delete = models.PROTECT)


    def __str__(self):
        return self.container_name

管理员端:

# admin.py

class ContainerAdmin(admin.ModelAdmin):
    list_display = ('container_name',)
    search_fields = ['container_name']
    filter_horizontal = ('samples',)
    list_per_page = 5 # No of records per page

class SampleAdmin(admin.ModelAdmin):
    list_display = ('sample_number',)
    search_fields = ['sample_number']
    list_per_page = 5 # No of records per page 


admin.site.register(Container, ContainerAdmin)
admin.site.register(Sample, SampleAdmin)

1 个答案:

答案 0 :(得分:1)

您可以修改ModelMultipleChoiceField的查询集。

class ContainerAdminForm(ModelForm):
    class Meta:
        model = Container
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        form = super().__init__(*args, **kwargs)
        # Limit samples to 10
        self.fields['samples'].queryset = Sample.objects.all()[:10]

class ContainerAdmin(admin.ModelAdmin):
    list_display = ('container_name',)
    search_fields = ['container_name']
    filter_horizontal = ('samples',)
    form = ContainerAdminForm