Django使用postgres支持jsonfield。
下面是基于JSON键(值匹配)过滤结果的示例。
OBJ1 : m1 = Movies.objects.create(movie_name='inception',movies_json_data{"review": "Mind Blowing", "rating": 5}
OBJ2 : m2 = Movies.objects.create(movie_name='joker',movies_json_data{"review": "horror", "rating": 4}
>>> Movies.objects.filter(movies_json_data__rating=5)
<QuerySet [<Movies: Inception>]>
当数据位于JSON结构之类的列表中时,如何执行过滤器查询?
movies_json_data=[{"review": "horror", "rating": 4},{"review":"horror-with-scify","rating":"4.5"}]
答案 0 :(得分:1)
对于一部电影,您可以执行以下操作:
kwargs = {
'movies_json_data__{}'.format('review'): 'horror',
'movies_json_data__{}'.format('rating'): 4
}
Movies.objects.filter(**kwargs)
因此,基本上,您现在可以编写一个for循环并执行常规方法。假设您想做一个OR
过滤器,以便获得与任何过滤器匹配的电影
from django.db.models import Q
q_objects = Q()
for data in movies_json_data:
kwargs = {}
for k, v in data.items():
kwargs['movies_json_data__{}'.format(k)] = v
q_objects.add(Q(**kwargs), Q.OR)
queryset = Movie.objects.filter(q_objects)