I have a function that filters a Django queryset on the number of linked objects. Used inside a graphene-django project, it allows me to dynamically create filter fields for a bunch of objects without writing super repetitive code.
The function works sometimes. When I pass mymodel_count__lt = 1, it only shows records with 0 linked mymodels. But when I pass mymodel_count__gte = 3, it is for some reason showing me records with only 2 linked mymodels. Am I missing something?
Here’s the function:
def filter_on_count_field(qs, **kwargs):
"""
Filters a queryset based on fields that end with the word "count" and their
corresponding values in kwargs.
"""
for filter_name, value in kwargs.items():
filter_field_name = filter_name.split("__")[0]
foreign_field_name = "_".join(filter_field_name.split("_")[:-1]) + "s"
if "__" not in filter_name or not filter_field_name.endswith("_count"):
continue
qs = qs.annotate(
**{filter_field_name: models.Count(foreign_field_name)}
).filter(**{filter_name: value})
return qs