I have the following code:
#models.py
class Repair(models.Model):
products = models.ManyToManyField(Product)
description = models.TextField()
def products_list(self):
return ', '.join([a.name for a in self.products.all()])
class Product(models.Model):
name = models.CharField(max_length=50,blank=False)
description = models.TextField(blank=True)
#admin.py
class RepairAdmin(admin.ModelAdmin):
list_display = ('products_list', 'description')
As you can see I use a custom model field with a join to show all repair related products on the ModelAdmin list_display property, this is working corretcly.
Now my question is: How I can make the custom field sortabe on the list_display? I only want to sort by the first item on the ManyToMany relashiontship. I tried to use the following code on the model:
products_list.admin_order_field = 'products__name'
Including this line I can activate the field sorting, but its not working correctly... When field sorting is requested it shows as many record duplications on the table as relations it has.
I've been researching and the closest thing to a solution I found is this:
Django admin: how to sort by one of the custom list_display fields that has no database field
But I dont see the correct way to apply it to my case.