Reputation: 263
I want to know how I can display the "highest value" from my ManyToMany Field in the admin. This is my models.py
file:
class Personal(models.Model):
lastname = models.CharField(max_length = 100)
firstname = models.CharField(max_length = 100)
degree = models.ManyToManyField('Degree')
def __str__(self):
return self.lastname
class Degree(models.Model):
name_degree = models.CharField(verbose_name = 'Degree', max_length = 200, blank = False)
rank = models.PositiveIntegerField(default = 0)
def __str__(self):
return self.name_degree
In my backed, I have created different types of Degree's, all with a "ranking". In my case, the highest degree you can have is "Doctoral Degree", with a rank of "6".
So if a User is creating himself in "Personal" he will have the option to select all the Degree's he has achieved. But for my Personal list, I just to want to see the highest one, e.g. if the User selects "Bachelor's Degree" and "Master's Degree", the Personal list should only contain "Master's Degree", because 5 > 4.
Someone with an idea on how my admin.py
file should look like?
class PersonalAdmin(admin.ModelAdmin):
list_display = ('lastname', 'firstname', ) # 'degree'
Upvotes: 1
Views: 176
Reputation: 477881
You can annotate the QuerySet
with the highest degree, and then define a method that will render that maximum:
from django.db.models import Max
class MyModelAdmin(admin.ModelAdmin):
list_display = ['lastname', 'firstname', 'max_degree']
def get_queryset(self, request):
queryset = super().get_queryset(request).annotate(
max_degree=Max('degree__rank')
)
def max_degree(self, obj):
return obj.max_degree
Upvotes: 1