2012-11-08 19 views
-1

我有列表(可能是一个或另一个迭代)的电子邮件字符串,我想获得所有模型的对象具有属性'电子邮件'匹配任何这些电子邮件。django queryset从列表或设置

我做:

from myapp.models import MyModel 
l=['[email protected]', '[email protected]', '[email protected]'] 
from django.db.models import Q 

q = Q(email=l[0]) 
for e in l[1:]: 
    q |= Q(email=e) 
MyModel.objects.get(q) 

有没有办法做到这一点更优雅?

+1

又见接受这个问题的答案:http://stackoverflow.com/a/352208/11527在以前的问题搜索时 – Ber

+0

@Ber没错没找到 – lajarre

回答

4

你可以使用:

MyModel.objects.filter(email__in=l) 
+2

https://docs.djangoproject.com/en/dev/ref/models/querysets/#in以供参考 – dm03514