簡體   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