【问题标题】:Django - filtering by a portion of the key within a listDjango - 通过列表中的部分键进行过滤
【发布时间】:2015-09-17 22:36:22
【问题描述】:

我在 django 1.8 表中有一些数据: “键”列值 = “a.2”、“b.4”、“c.6” 我想通过 ["a", "b"] 过滤它并忽略点后面的部分。

Blog.objects.filter(key__startswith=['a','b'])

什么都不返回

Blog.objects.filter(key__contains=['a','b'])

什么都不返回

Blog.objects.filter(key__in=['a%','b%'])

什么都不返回

有没有比循环更有效的方法来做到这一点?

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    您可以尝试使用Q 对象:

    from django.db.models import Q
    Blog.objects.filter(Q(key__startswith='a') | Q(key__startswith='b'))
    

    https://docs.djangoproject.com/en/1.8/topics/db/queries/#complex-lookups-with-q

    或使用regexiregex

    Blog.objects.filter(key__iregex=r'^(a|b)\.')
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-03
    • 2018-03-02
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2020-09-28
    • 2017-05-16
    • 2013-09-11
    相关资源
    最近更新 更多