[英]How do I make a query where it filters everything that starts with a number in Django?
[英]How do I make a Django database query that has multiple filters?
我有一个艺术家和绘画数据库,我想根据艺术家名称和绘画标题进行查询。 标题位于json文件中(艺术家名称来自ajax),因此我尝试了循环。
def rest(request):
data = json.loads(request.body)
artistname = data['artiste']
with open('/static/top_paintings.json', 'r') as fb:
top_paintings_dict = json.load(fb)
response_data = []
for painting in top_paintings_dict[artist_name]:
filterargs = {'artist__contains': artistname, 'title__contains': painting}
response_data.append(serializers.serialize('json', Art.objects.filter(**filterargs)))
return HttpResponse(json.dumps(response_data), content_type="application/json")
它不会返回我需要的对象列表,而只是返回一些对任何人都没有好处的难看的双序列化json数据。
["[{\"fields\": {\"artist\": \"Leonardo da Vinci\", \"link\": \"https://trove2.storage.googleapis.com/leonardo-da-vinci/the-madonna-of-the-carnation.jpg\", \"title\": \"The Madonna of the Carnation\"}, \"model\": \"serve.art\", \"pk\": 63091}]",
这个处理程序可以工作并返回我为艺术家准备的每幅画。
def rest(request):
data = json.loads(request.body)
artistname = data['artiste']
response_data = serializers.serialize("json", Art.objects.filter(artist__contains=artistname))
return HttpResponse(json.dumps(response_data), content_type="application/json")
我只需要按标题和艺术家过滤查询。
in您的问题是您要两次将数据serializers.serialize
json.dumps
一次使用serializers.serialize
,然后再次使用json.dumps
。
我不知道您的应用程序的细节,但是可以在Django中链接过滤器。 所以我将采用您的第二种方法,只是替换行
response_data = serializers.serialize("json", Art.objects.filter(artist__contains=artistname))
与
response_data = serializers.serialize("json", Art.objects.filter(artist__contains=artistname).filter(title__in=paintings))
查看queryset文档 。
对__contains
进行绘画标题搜索的最有效方法是对所有可能的绘画名称使用Q
对象 or
将Q
对象一起使用:
from operator import or_
def rest(request):
data = json.loads(request.body)
artistname = data['artiste']
with open('/static/top_paintings.json', 'r') as fb:
top_paintings_dict = json.load(fb)
title_filters = reduce(or_, (Q(title__contains=painting) for painting in top_paintings_dict[artist_name]))
paintings = Art.objects.filter(title_filters, artist__contains=artist_name)
这将为您提供绘画查询集。 我怀疑您的双重序列化是不正确的,但在单一艺术家姓名的情况下,您似乎对此感到满意,因此我将由您自己决定。
这里的reduce
调用是建立|
结果的方法|
将多个Q
对象组合在一起operator.or_
是|
的功能句柄。 ,然后使用生成器表达式为每个绘画名称创建一个Q
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.