I'm using Django 2.1 and I need to add a list filter on model(#1) admin page referencing a field from a different model(#2)(which has a foreign key referencing the current model(#1) These are my 2 models:
class ParentProduct(models.Model):
parent_id = models.CharField(max_length=255, validators=[ParentIDValidator])
name = models.CharField(max_length=255, validators=[ProductNameValidator])
parent_slug = models.SlugField(max_length=255)
parent_brand = models.ForeignKey(Brand, related_name='parent_brand_product', blank=False, on_delete=models.CASCADE)
...
class ParentProductCategory(models.Model):
parent_product = models.ForeignKey(ParentProduct, related_name='parent_product_pro_category', on_delete=models.CASCADE)
category = models.ForeignKey(Category, related_name='parent_category_pro_category', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
Here is my admin class for model 'ParentProduct':
class ParentProductAdmin(admin.ModelAdmin):
resource_class = ParentProductResource
form = ParentProductForm
class Media:
pass
change_list_template = 'admin/products/parent_product_change_list.html'
actions = [deactivate_selected_products, approve_selected_products]
list_display = [
'parent_id', 'name', 'parent_brand', 'product_hsn', 'gst', 'product_image', 'status'
]
inlines = [
ParentProductCategoryAdmin
]
list_filter = [ParentBrandFilter, 'status']
Here is the ParentBrandFilter:
class ParentBrandFilter(AutocompleteFilter):
title = 'Brand'
field_name = 'parent_brand'
This works correctly because the field 'parent_brand' exists on my model 'ParentProduct'. How do I get the same autocomplete type list filter for the field category which is actually inside the 'ParentProductCategory' model.
Note: 'ParentProductCategory' -> 'ParentProduct' is a many-to-one mapping.
Note #2: Django admin add custom filter. I tried going through this question but couldn't get through with the approach and also my requirement is different. I need an autocomplete type filter.
Note #3: If autocomplete is not possible, is there a way to have a dropdown with only existing 'category' values in it?
try this in your ParentProductAdmin class