[Fixed]-Django admin changelist filtering / link to other models

4👍

I think your approach to display the list_children column is correct. Don’t worry about the ‘link hacking’, it’s fine.

To display a column for indicate whether any of the object’s children has toys, just define another method on the ParentAdmin class, and add it to list_display as before.

class ParentAdmin(admin.ModelAdmin):
    list_display = ('id', 'some_col', 'some_other', 'list_children', 'children_has_toys')
    ...
    def children_has_toys(self, obj):
        """
        Returns 'yes' if any of the object's children has toys, otherwise 'no'
        """
        return ToyModel.objects.filter(child_owner__parent=obj).exists()
    children_has_toys.boolean = True

Setting boolean=True means Django will render the ‘on’ or ‘off’ icons as it does for boolean fields. Note that this approach requires one query per parent (i.e. O(n)). You’ll have to test to see whether you get acceptable performance in production.

Leave a comment