Django admin外键下拉列表,带排序

2024-10-05 17:47:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在django有个模特

class NotificationMapping(models.Model):
    counterId = models.ForeignKey(CounterDetails)
    groupId = models.ForeignKey(CounterGroup)


class Meta:
    unique_together = ('counterId', 'groupId',)

模型管理员:

^{pr2}$

我需要从添加新条目的地方对外键下拉列表中的值进行排序。在

Counter Id dropdown image


Tags: django模型modelmodels管理员metaclassunique
1条回答
网友
1楼 · 发布于 2024-10-05 17:47:34

您可以这样做:

class NotificationMappingAdmin(admin.ModelAdmin):
    list_display = ['get_counterId', 'get_groupId',]
    ordering = ('id',)

    def get_form(self, request, obj=None, **kwargs):
        form = super(NotificationMappingAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['get_counterId'].queryset = CounterDetails.objects.all().order_by('-id')
        form.base_fields['get_groupId'].queryset = CounterGroup.objects.all().order_by('-id')

        return form

相关问题 更多 >