[英]django queryset from a list or set
I am having list (could be a set or another iterable) of, say, emails strings, and I want to get all of a models' objects that have attribute 'email' matching any of those emails. 我有电子邮件字符串的列表(可以是一个集合或另一个可迭代的列表),并且我想获取所有模型对象,这些对象的属性“电子邮件”与这些电子邮件中的任何一个匹配。
I am doing: 我在做:
from myapp.models import MyModel
l=['email1@x.com', 'email2@x.com', 'email3@y.com']
from django.db.models import Q
q = Q(email=l[0])
for e in l[1:]:
q |= Q(email=e)
MyModel.objects.get(q)
Is there a way to do it more elegantly? 有没有办法更优雅地做到这一点?
您可以使用:
MyModel.objects.filter(email__in=l)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.