允许在list_display中显示属性字段

时间:2020-08-26 11:23:14

标签: python django django-admin

我正在尝试在django管理员list_display中设置订购,但我无法使其正常工作。我已经尝试过使用queryset批注,但是还没有找到如何使用模型属性对其进行批注。

代码: models.py

class Person(models.Model):
    name = models.CharField(max_length=150, verbose_name='Nome Próprio')
    dob = models.DateField(verbose_name="Date of birth")
    
    @property
    def age(self):
        born = self.dob
        today = date.today()
        return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

admin.py

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
list_display = ['name', 'dob', 'age']

def get_queryset(self, request):
    qs = super(PersonAdmin, self).get_queryset(request)
    qs = qs.annotate(age='age')
    return qs

到目前为止,这是我的尝试,有没有简单的解决方法?我是Django的新手。 谢谢

1 个答案:

答案 0 :(得分:0)

这应该有效:

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_display = ['name', 'dob', 'age']
    
    def age(self, obj):
        born = self.dob
        today = date.today()
        return today.year - born.year - ((today.month, today.day) < (born.month, born.day)
    age.admin_order_field = 'dob' # set the field that is used for ordering
    age.short_description = 'Age' # set the name of the column

有关Django's ModelAdmin.list_display文档的更多信息。