【问题标题】:Django admin foreign key dropdown with sortingDjango admin外键下拉列表与排序
【发布时间】:2017-04-06 01:40:40
【问题描述】:

我在 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

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

Counter Id dropdown image

【问题讨论】:

  • 按什么排序?您甚至没有发布相关模型。
  • 我想按字母顺序对下拉列表中的值进行排序
  • @ManojMali 你能解决这个问题吗?

标签: python django django-admin


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 你也可以只修改查询集而不是指定一个新的:form.base_fields['get_counterId'].queryset = form.base_fields['get_counterId'].queryset.order_by('-id')
猜你喜欢
  • 2018-10-27
  • 2012-02-18
  • 1970-01-01
  • 2013-09-15
  • 1970-01-01
  • 2012-07-05
  • 2020-06-19
  • 2011-03-05
  • 1970-01-01
相关资源
最近更新 更多