如何在 django admin 中对不存在的字段进行排序/排序

Str*_*ker 2 django

如何在 django admin 中对不存在的字段进行排序。基本上我有服务器和应用程序模型,第三个关系模型将它们链接起来。我看到了您的回复,但不确定将您提到的代码放在哪里。这是模型和admin.py

# Model.py File
class Server(models.Model):
name = models.CharField(max_length=100,  unique=True)
operating_system = models.CharField(max_length=20, choices=constants.OPERATING_SYSTEMS.items())

@property
def number_of_apps(self):
    return ServerApplicationRelationship.objects.filter(server=self).count()

class Application(models.Model):
    name = models.CharField(max_length=100,  unique=True)
hosted_on = models.ManyToManyField(Server, through='ServerApplicationRelationship', blank=True,)

@property
def number_of_servers(self):
    return ServerApplicationRelationship.objects.filter(app=self).count()
# number_of_servers.server_field = 'server__count'

class ServerApplicationRelationship(models.Model):
    server = models.ForeignKey(Server, blank=True, )
    # server_tag = models.ForeignKey(Server, through_fields= 'tags')
    app = models.ForeignKey(Application, blank=True)

# Admin.py file
@admin.register(Application)
class ApplicationAdmin(admin.ModelAdmin):


    inlines = [ApplicationInLine]
    list_display = ['name', 'number_of_servers']
    list_display_links = ['name', 'number_of_servers']

    ordering = ('number_of_servers', 'name')

@property
def number_of_apps(self):
    queryset = ServerAppRelation.objects.filter(server=self).count()
    return queryset
Run Code Online (Sandbox Code Playgroud)

如果我number_of_serversordering. 我收到一个错误

    ERRORS:
<class 'S5.admin.ApplicationAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'number_of_server', which is not an attribute of 'S5.Appl
ication'
Run Code Online (Sandbox Code Playgroud)

number_of_server 显示为表中的列,但不可排序。我怎样才能使它可排序?

非常感谢

Ala*_*air 8

首先,您需要覆盖该get_queryset方法,并使用服务器数量对其进行注释。

不幸的是,您不能在 中包含带注释的字段list_display,因为它未通过 Django 系统检查。因此,您定义了一个返回带注释字段的方法,并将该方法包含在list_display.

最后,为了使列可排序,您需要admin_order_field在方法上设置属性。

@admin.register(Application)
class ApplicationAdmin(admin.ModelAdmin):
    list_display = ['name', '_num_servers']

    def _num_servers(self, obj):
        return obj.num_servers
    _num_servers.admin_order_field = 'num_servers'

    def get_queryset(self, request):
        return super(AppAdmin, self).get_queryset(
            request,
        ).annotate(num_servers=Count('servers'))
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

2547 次

最近记录:

9 年,10 月 前