Home:ALL Converter>How to check if many-to-many list is empty with django-filter?

How to check if many-to-many list is empty with django-filter?

Ask Time:2017-07-21T18:54:03         Author:okarimov

Json Formatter

I am using django-rest-framework with django-filter to implement filtering. Let's say I have following result:

{
    "id": 13,
    "created": "2017-06-21T01:08:49.790254Z",
    "updated": "2017-07-21T10:25:51.706730Z",
    "toylist": [],
}

How do I implement filtering so I can check if the toylist array is empty? For example, something like: /toys/?toylist__isnull=True

Author:okarimov,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/45235852/how-to-check-if-many-to-many-list-is-empty-with-django-filter
okarimov :

Ok, it was a relatively simple fix:\n\nclass ToysFilter(filters.FilterSet):\n toylist__isnull = filters.BooleanFilter(name='toylist', method='list_is_empty')\n\nclass Meta:\n model = Toys\n fields = {\n 'id':['exact'],\n 'created':'__all__',\n 'updated':'__all__',\n }\n\ndef list_is_empty(self, qs, name, value):\n isnull = not value\n lookup_expr = LOOKUP_SEP.join([name, 'isnull'])\n\n return qs.filter(**{lookup_expr: isnull}).distinct()\n",
2017-07-26T12:23:20
yy