📜  custom-field-list_display - Python (1)

📅  最后修改于: 2023-12-03 15:00:11.006000             🧑  作者: Mango

Custom Field List Display - Python

Custom Field List Display is a feature in Django that allows the developer to define custom list displays for the admin site. This feature is useful when the developer wants to display additional information about the objects listed in the admin site.

Defining Custom List Displays

To define a custom list display, the developer needs to define a method in the model admin class with the list_display attribute.

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'custom_field')
    
    def custom_field(self, obj):
        return obj.my_custom_field
    custom_field.admin_order_field = 'my_custom_field'
    custom_field.short_description = 'My Custom Field'

In the above code, the list_display attribute is set to include the model's __str__() method and a custom field defined in the custom_field() method. The custom_field() method takes an obj parameter, which represents the object being listed in the admin site. The method returns the value of the custom field for the object.

The admin_order_field attribute is used to specify the name of the database field to use when sorting the list of objects by the custom field. The short_description attribute is used to specify the name of the column header to use in the admin site.

Conclusion

Custom Field List Display is a powerful feature in Django that allows the developer to display additional information about the objects listed in the admin site. By defining a custom method in the model admin class and setting the list_display attribute, the developer can easily create custom list displays for their admin site.