0

I want to know how I can display the highest ranking from the model education in the staff. The user would be able to select all of their educations, but for me it's irrelevant to know if the the user selected "high school" when he/she also has a master's degree.

class Staff(models.Model):
    education = models.ManyToManyField('Education', verbose_name = 'Education')
class Education(models.Model):
    name = models.CharField(max_length = 200, blank = False)
    rank = models.PositiveIntegerField(default = 0)

    def __str__(self):
        return self.name

I gave every type of education a ranking.

So in the Admin, the only thing I want returned would be the highest eduacation by a member of the staff - how do I write this function?

class StaffAdmin(admin.ModelAdmin):
    list_display = ('rank', )
schuhesindbequemer
  • 243
  • 1
  • 3
  • 12
  • See this answer https://stackoverflow.com/questions/18108521/many-to-many-in-list-display-django. You can't access it directly, but can write custom method to display whatever you want. Also see Django documentation https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display – Dmitry Apr 26 '21 at 11:50
  • do you know what the code would look like? and where would I put it. thank you btw!!! – schuhesindbequemer Apr 26 '21 at 12:01

1 Answers1

0

NOTE: this code is not tested, it's just to show you the of the possible solutions.

You can use @admin.display decorator (see Django docs). You also should modify get_queryset() method so you retrieve ranks for all Staff objects and won't hit a database for every row. So your code will look something like that

class StaffAdmin(admin.ModelAdmin):
    list_display = ('highest_rank', )
    
    @admin.display(description="Employee's highest education rank")
    def highest_rank(obj):
       top_rank = obj.Education.order_by("-rank").first()  # may return None
       return rank.name

    def get_queryset(self, request):
        qs = super(StaffAdmin, self).get_queryset(request)
        # get related model so we don't hit database for every Staff row
        return qs.prefetch_related("Education")
Dmitry
  • 146
  • 3