我正在尝试使用django-filters使用filter方法
请参阅以下模型的示例:
class Chicken(TimeStampedModel):
eggs = ForeignKey(Egg)
class Egg(TimeStampedModel):
hatched = BooleanField(default=False)
请参阅我当前为过滤器设置的示例:
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)
问题是该方法甚至无法打印当我点击网址时,我们收到了鸡蛋。它只是返回一个空的查询集。
最佳答案
我像上面那样做:
在我的网址中,我发送了类似?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
关于python - 将自定义过滤器与Django ModelChoice过滤器一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43009538/