繁体   English   中英

Django admin外键下拉列表与排序

[英]Django admin foreign key dropdown with sorting

我在 django admin 中有一个模型,如下所示:

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


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

模型管理员:

class NotificationMappingAdmin(admin.ModelAdmin):
    list_display = ('get_counterId', 'get_groupId',)
    actions = None

    # if display name is available for the counter display it
    # if not display counterId
    def get_counterId(self, obj):
        if obj.counterId.displayName:
            return obj.counterId.displayName
        else:
            return obj.counterId.counterId
    get_counterId.admin_order_field  = 'counterId'  # Allows column order sorting
    get_counterId.short_description = 'counter'  # Renames column head

    # show groupId on admin page for notification mapping
    def get_groupId(self, obj):
        return obj.groupId.groupId
    get_groupId.admin_order_field  = 'groupId'  # Allows column order sorting
    get_groupId.short_description = 'groupId'  # Renames column head

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

计数器 ID 下拉图片

你可以这样做:

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

您可以覆盖formfield_for_foreignkey()进行排序,如下所示:

class NotificationMappingAdmin(admin.ModelAdmin):
    list_display = ('get_counterId', 'get_groupId',)
    actions = None

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        formfield = super().formfield_for_foreignkey(db_field, request, **kwargs)
        if db_field.name == "get_counterId":            
            formfield.queryset = CounterDetails.objects.all().order_by('-id')        
        
        if db_field.name == "get_groupId":            
            formfield.queryset = CounterGroup.objects.all().order_by('-id')
        
        return formfield

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM