Custom filters in the administration panel

Hi Django Community!!!

I’ve been working with Django for a short time and I come to you to solve a little problem I have.

I have a “RecipeRequirement” model, which looks like this:

class RecipeRequirement(models.Model):
    menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE)
    ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
    quantity = models.FloatField(default=0.0)
    
    def __str__(self):
        return f'#{self.id}'
    
    def clean(self):
        if self.quantity < 0:
            raise ValidationError('You cannot have a recipe requirement with a quantity less than zero.')
        
    class Meta:
        verbose_name = 'Recipe Requirement'
        verbose_name_plural = 'Recipe Requirements'

As you can see, two of the fields of the model are of type “ForeignKey” and refer to the “Ingredient” and “MenuItem” models.

In the Django admin panel, I want to add two filters for this template: one with the “ingredient” field and another with the “menu_item” field. For this, I have created the “RecipeRequirementAdmin” class:

class RecipeRequirementAdmin(admin.ModelAdmin):
    list_display = ['__str__', 'ingredient', 'menu_item']
    list_filter = [
        ('ingredient', admin.RelatedOnlyFieldListFilter),
        ('menu_item', admin.RelatedOnlyFieldListFilter),
    ]

Well, as you can see in the screenshot below, the filters with the records of the “Ingredient” model appear without problem, but the filters of the “MenuItem” model do not:

Could someone help me to find the reason why this is happening?

In advance, I appreciate the time you can dedicate to this problem and the help you can give me.

P.S.: To clarify, that I have another model “Purchase” that also has a field of the type “ForeignKey” making reference to the model “MenuItem”. Could this have some kind of relation with the problem?

From the docs at Using a field name and an explicit FieldListFilter

List filters typically appear only if the filter has more than one choice. A filter’s has_output() method controls whether or not it appears.

The sample data you’re showing only shows one menu item, pizza. If pizza is the only item on the menu (which isn’t a bad thing), then the filter doesn’t need to appear.

1 Like

Hi @KenWhitesell!!!

Thank you very much for your quick response. I have tried adding a new item and indeed the filters already appear :slight_smile: .