當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Django display用法及代碼示例

本文介紹 django.contrib.admin.display 的用法。

聲明

display(*, boolean=None, ordering=None, description=None, empty_value=None)
Django 3.2 中的新函數。

此裝飾器可用於設置自定義顯示函數的特定屬性,可與 list_display readonly_fields 一起使用:

@admin.display(
    boolean=True,
    ordering='-publish_date',
    description='Is Published?',
)
def is_published(self, obj):
    return obj.publish_date is not None

這相當於直接在函數上設置一些屬性(使用原始的、更長的名稱):

def is_published(self, obj):
    return obj.publish_date is not None
is_published.boolean = True
is_published.admin_order_field = '-publish_date'
is_published.short_description = 'Is Published?'

另請注意,empty_value 裝飾器參數映射到直接分配給函數的empty_value_display 屬性。它不能與boolean 一起使用——它們是互斥的。

使用這個裝飾器不是必須的來創建一個顯示函數,但是在你的源代碼中使用它而不帶參數作為一個標記來識別函數的目的是很有用的:

@admin.display
def published_year(self, obj):
    return obj.publish_date.year

在這種情況下,它不會向函數添加任何屬性。

相關用法


注:本文由純淨天空篩選整理自djangoproject.com大神的英文原創作品 django.contrib.admin.display。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。