【发布时间】:2016-04-21 08:07:29
【问题描述】:
如何在 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
如果我在ordering 中包含number_of_servers。我收到一个错误
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 在表中显示为列,但不可排序。 如何使其可排序?
非常感谢
【问题讨论】:
-
@Brandon 重复的目标已经有好几年了,而且有点过时了。现在正确的做法是使用
annotate而不是extra。 -
好的,我重新打开了。
-
请参阅上面的详细信息。不知道如何修改代码以使其可排序。
-
@Alasdair,您能否提供一个基于注释的示例代码,说明您将如何使用它?
标签: django