Search code examples
django-admindjango-admin-filtersdjango-admin-actions

Filter to show "null" relations (where no results related to the item)


Quite simply, django filter (standard) give you the option to see "All". I want to create an option to show items which contain "None"

The query would be something like this:

tags = Product.objects.exclude(tag__isnull=True)

My models.py

class Tag(models.Model):
    name = models.CharField(max_length=100, blank=False)
    def __unicode__(self):
        return self.name

class Product(models.Model):
    name = models.CharField ("Name", max_length=400)
    tag = models.ManyToManyField(Tag, blank=True)
    def __unicode__(self):
       return self.name

How would I achieve this? I tried a SimpleListFilter, however this just listed all the items in a filter. I want the items to show up in the admin page view. Can an Admin action do this?


Solution

  • I've just figured it out- Django does this automatically using "list_filter". But it only works if you use the tag (self name as defined in models.py), and not the way I had it as below.

    All I had to do was change

    list_filter: ('tag__name')
    

    to

    list_filter: ('tag')
    

    That is the stock method of showing Django filters. It allows me to see All & (none)