How can sort on a non-existent field in django admin. Basically I have server and app model with a third relationship model linking them. I saw your responses but not sure where to place the code you have mentioned. Here are the model and 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
If I include the number_of_servers
in the ordering
. I get an error
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 is displayed in as column in the table but is not sortable. How can I make it sortable?
Many thanks