[Django]-Using filters with model inheritance

2👍

Add to your BaseProduct

 class Meta:
    abstract = True

https://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes

Base model will not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class.

https://django-filter.readthedocs.org/en/latest/usage.html#the-filter

Just like with a ModelForm we can also override filters, or add new ones using a declarative syntax

class BaseProductFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_type='icontains')
    cost = django_filters.NumberFilter(lookup_type='lt')


class FoodProductFilter(BaseProductFilter):
    farmer = django_filters.CharFilter(lookup_type='icontains')

    class Meta:
        model = FoodProduct
        fields = ['name', 'cost', 'farmer']


class ClothingProductFilter(BaseProductFilter):
    # size lookup_type will be 'exact'
    class Meta:
        model = ClothingProduct
        fields = ['name', 'cost', 'size']

Leave a comment