7

I am trying to create use the filter method with django-filters

See an example of the models below:

class Chicken(TimeStampedModel):
    eggs = ForeignKey(Egg)

class Egg(TimeStampedModel):
    hatched = BooleanField(default=False)

See an example of my current set up for the filter:

class ChickenFilter(FilterSet):
    eggs__contains = ModelChoiceFilter(name="eggs", method='hatched_eggs', queryset=Eggs.objects.all())

   def hatched_eggs(self, queryset, name, value):
      print "We got eggs"
     return queryset.filter(eggs__hatched=True)

The problem is that the method doesnt even print We got eggs when I hit the url. It just returns an empty queryset.

2
  • What is the querystring that you're using? If eggs__contains isn't in the querystring, the filter won't execute. Commented Mar 26, 2017 at 0:09
  • I am going through similar issue. Did you fix your problem? Commented Sep 18, 2017 at 13:36

2 Answers 2

9

I did it like below:

In my urls I sent ?ids=1,2,3,4

class MyFilter(filters.FilterSet):
    ids = django_filters.CharFilter(method='ids__in')

    def ids__in(self, queryset, value, *args, **kwargs):
        try:
            if args:
                ids = args[0].split(',')
                ids = [int(_id) for _id in ids]
                queryset = queryset.filter(id__in=ids)
        except ValueError:
            pass
        return queryset
Sign up to request clarification or add additional context in comments.

Comments

4

I was going through the same problem. My method was not being called.

So came to conclusion, I can make a workaround using:

Using custom methods in filter with django-rest-framework

class ChickenFilter(FilterSet):
    eggs__contains = CharFilter(action='hatched_eggs')

def hatched_eggs(queryset, value):
      print "We got eggs"
     if value:
         return queryset.filter(eggs__hatched=True)
     return queryset

1 Comment

action didnt work for me, i've used method instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.