查询其json字段具有过滤器值的所有对象

时间:2019-05-14 18:32:09

标签: django-rest-framework

Models.py


class Apply(models.Model):
    name = models.CharField(max_length=20)
    role = JSONField()

    def __str__(self):
        return self.name

如何编写一个过滤器,以使其角色字段(json)的所有对象都具有过滤器值:

API:GET-/ api / application /?role = efgh应该检索ID为的条目 以下的1和2:

+----+--------+---------------------+
| id | name   |role                 |
+----+--------+---------------------+
|  1 | abcd   |["abcd", "efgh"]     |
|  2 | abcd   |["efgh", "ijkl"]     |
|  3 | abcd   |["ijkl", "abcd"]     |
+----+--------+---------------------+

1 个答案:

答案 0 :(得分:0)

尝试一下:

role = request.query_params.get('role')
Apply.objects.filter(role__icontains=role)

https://docs.djangoproject.com/en/2.1/ref/models/querysets/#icontains