简体   繁体   中英

Django admin foreign key dropdown with sorting

I have a model in django admin like below:

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


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

ModelAdmin:

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

I need to sort the values in the foreign key dropdown from where we add new entry.

Counter Id dropdown image

You can do this:

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

You can override formfield_for_foreignkey() for sorting as shown below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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