我正在尝试在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的新手。 谢谢
答案 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文档的更多信息。