Reputation: 21
I have two models, one (Device) which has a foreign key to the other (Storage). In the admin overview of Storage I wanna be able to add a count of how many Device has pointed to each Storage. Using the code below I'm able to correctly count the number of Devices pointing to each Storage. However, when trying to sort by the number in storage it crashes with the following error:
Cannot resolve keyword '_get_device_number' into field. Choices are: ... #List of fields
How do I add my calculated field into the list allowed searches?
class Device(models.Model):
...
storage_id = models.ForeignKey(Storage, on_delete=models.PROTECT, blank=True,null=True) #Allowed to be null since a Device may not be in storage.
class Storage(models.Model):
...
def _get_device_number(self,):
return Device.objects.filter(storage_id=self.storage_id).count()
class StorageAdmin(admin.ModelAdmin):
...
list_display = ['__str__', 'get_device_number',]
def get_device_number(self, obj):
return obj._get_device_number()
get_device_number.admin_order_field = '_get_device_number'
Upvotes: 2
Views: 1051
Reputation: 1355
The admin list view cannot access a model method. However, annotating the admin queryset does work.
class StorageAdmin(admin.ModelAdmin):
def get_queryset(self, request):
queryset = super().get_queryset(request)
queryset = queryset.annotate(
_get_device_number=Count('device')
)
return queryset
def get_device_number(self, obj):
return obj._get_device_number
get_device_number.admin_order_field = '_get_device_number'
Upvotes: 2