我正在实施一个一次性数据导入器,我需要在其中搜索现有的 slug。蛞蝓在一个数组中。将数组转换为OR
查询的公认最佳实践方式是什么?
我想出了以下方法,它有效,但感觉代码太多,无法完成这么简单的事情。
# slug might be an array or just a string
# ex:
slug = [ "snakes", "snake-s" ] # in the real world this is generated from directory structure on disk
# build the query
query = MyModel.objects
if hasattr(slug, "__iter__"):
q = Q()
for s in slug:
q = q.__or__(Q(slug=s))
query = query.filter(q)
else:
query = query.filter(slug=slug)