简体   繁体   English

Django ManyToMany 字段管理员显示最高值

[英]Django ManyToMany Field admin display highest value

I want to know how I can display the "highest value" from my ManyToMany Field in the admin.我想知道如何在管理员的 ManyToMany 字段中显示“最高值”。 This is my models.py file:这是我的models.py文件:

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".就我而言,您可以获得的最高学位是“博士学位”,排名为“6”。 支持教育的管理员列表

So if a User is creating himself in "Personal" he will have the option to select all the Degree's he has achieved.因此,如果用户在“个人”中创建自己,他将可以选择 select 他已获得的所有学位。 But for my Personal list, I just to want to see the highest one, eg if the User selects "Bachelor's Degree" and "Master's Degree", the Personal list should only contain "Master's Degree", because 5 > 4.但是对于我的个人列表,我只想看到最高的,例如如果用户选择“学士学位”和“硕士学位”,则个人列表应该只包含“硕士学位”,因为 5 > 4。

Someone with an idea on how my admin.py file should look like?有人知道我的admin.py文件应该是什么样子吗?

class PersonalAdmin(admin.ModelAdmin):
    list_display = ('lastname', 'firstname', ) # 'degree'

You can annotate the QuerySet with the highest degree, and then define a method that will render that maximum:您可以用最高程度注释QuerySet ,然后定义一个将呈现该最大值的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM