Django Admin Cookbook-28-many or how to display coupled reverse field on the page list view

28. How to display a reverse-many join field or on the list view page?

For Hero object, you can use the following self-join fields to track its parent objects:

father = models.ForeignKey(
    "self", related_name="children", null=True, blank=True, on_delete=models.SET_NULL
)

Suppose you are asked to show the subordinate object for each Hero in the list view page. Hero coupled reverse field object has children, but it can not be added to list_display management model. You need to add additional properties to ModelAdmin, and use the property in list_display in. Examples are as follows:

@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
    ...
    def children_display(self, obj):
        return ", ".join([
            child.name for child in obj.children.all()
        ])
    children_display.short_description = "Children"

You will see a column sub-object display, shown below:

You can also use the same method to-many relationship. You can also read, how to get a particular object Django Admin background url?

Back to Contents

Guess you like

Origin www.cnblogs.com/superhin/p/12187219.html