Search code examples
djangodjango-filter

Django - PropertyFilterSet - How to filter on a property when the property refers to a model


How can I filter on a model's property with django_property_filter package given the following Django models:

# models.py
from django.db import models

class Manager(models.Model):
    name = models.CharField(max_length=35)

class Plan(models.Model):
    name = models.CharField(max_length=35)
    manager = models.ForeignKey(Manager, on_delete=models.CASCADE)

class Member:
    name = models.CharField(max_length=35)
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)

    @property
    def manager(self):
        return self.plan.manager


# filters.py
from django_property_filter import PropertyFilterSet

    class Meta:
        model = Member
        fields = []

    class MemberFilter(PropertyFilterSet):
        manager = ???(
        field_name='manager',
        )

I tried the PropertyMultipleChoiceFilter and PropertyChoiceFilter with no success. Choices was set to [(m.pk, m.name) for m in Manager.objects.all()].


Solution

  • To filter on a model’s property with django_property_filter, you need to use the PropertyModelChoiceFilter or PropertyModelMultipleChoiceFilter, which accept a queryset as the choices parameter. For example, you can write:

    from django_property_filter import PropertyFilterSet, PropertyModelChoiceFilter
            
    
    class MemberFilter(PropertyFilterSet):
          manager = PropertyModelChoiceFilter(
                    field_name='manager',
                    queryset=Manager.objects.all(),
                          to_field_name='name',
                     )
    
    class Meta:
        model = Member
        fields = []