如何在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
如果我在number_of_servers
中加入ordering
。我收到错误
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'
number_of_server显示在表格的列中,但不可排序。 我怎样才能让它排序?
非常感谢
答案 0 :(得分:2)
首先,您需要覆盖select
Case when Remainder (rownum,3)=0 then 'Fizz'
when Remainder (rownum,5)=0 then 'Buzz'
when (remainder (rownum,3)=0 and remainder(ROWNUM,5) = 0) then 'FizzBuzz'
else to_char(rownum) end
from DUAL
Connect by level <=100;
方法,并使用服务器数量对其进行注释。
不幸的是,您无法在get_queryset
中包含带注释的字段,因为它无法通过Django系统检查。因此,您定义一个返回带注释字段的方法,并在list_display
中包含该方法。
最后,要使列可订购,您需要在方法上设置list_display
属性。
admin_order_field