【问题标题】:Django filter iexact on a listDjango 过滤 iexact 列表
【发布时间】:2016-03-04 13:01:57
【问题描述】:

我有一个这样设置的用户模型。

class ExternalUserModel(models.Model):
    email = models.EmailField()
    # other fields

class MyUserModel(models.Model):
    external_user = models.ForeignKey(ExternalUserModel)
    # other fields

我正在尝试从电子邮件列表中获取 MyUserModel 列表。

这是我要执行的查询:

MyUserModel.objects.filter(external_user__email__iexact__in=user_emails)

但是我收到了这个错误: Unsupported lookup 'iexact' for EmailField or join on the field not permitted.

我需要 iexact,因为电子邮件列表基于用户输入,可能与存储在数据库中的大小写不匹配。

我应该如何进行这个查询?

【问题讨论】:

    标签: python django django-queryset


    【解决方案1】:

    Django ORM 不直接支持。我不认为数据库后端也这样做。您可以通过组合多个 __iexact 过滤器来获得所需的结果,如此处的各种答案所示:How to dynamically compose an OR query filter in Django?

    在此处显示的选项中,我更喜欢 reduce(operator.or_, ...) 语法而不是 for 循环,但这是个人偏好。

    【讨论】:

    • 谢谢! query = reduce(operator.or_, (Q(external_user__email__iexact=x) for x in user_emails)) MyUserModel.objects.filter(query) 成功了!
    【解决方案2】:

    电子邮件必须是完整的,因此,它应该是准确的,您不需要使用__iexact 查找。你只需要:

    MyUserModel.objects.filter(external_user__email__in=user_emails)
    

    【讨论】:

    • 这里会考虑大小写,即email@example.comEmail@example.com不同
    猜你喜欢
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2017-03-27
    • 2020-08-02
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多