[Fixed]-Limit the queryset of entries displayed for a django admin Inline


As benjaoming mentioned in the comments, it was necessary to override the get_queryset() method in the InlineModelAdmin. It was not necessary to override and attach a new formset to the InlineModelAdmin definition as I initially thought.

Here is the resulting implementation:

class ChangeCommentInline(admin.StackedInline):
    """For allowing logged in user to add change comment"""
    model = ChangeComment
    extra = 1
    exclude = ("user", ) # auto-update user field in save_formset method of parent modeladmin.

    def get_queryset(self, request):
        """Alter the queryset to return no existing entries"""
        # get the existing query set, then empty it.
        qs = super(ChangeCommentInline, self).get_queryset(request)
        return qs.none()  


I am supposing you are using a


in your ChangeComment model. but if you want only one comment for each EntryAdmin, your should use instead a:


And you won’t need your NoCommentsInlineFormset nor your inline class.
That’s what I would do.


Ok then if you want to keep a history of comments, you could override the queryset in the NoCommentsInlineFormset

def __init__(self, *args, **kwargs):
    super(NoCommentsInlineFormset, self).__init__(*args, **kwargs)
    self.queryset = ChangeComment.objects.order_by('-created_at')[:1]

This should work.

Leave a comment