我希望能够列出用户已添加的项(它们被列为创建者)或已批准的项。

所以我基本上需要选择:

item.creator = owner or item.moderated = False

在Django中如何做到这一点?(最好是带有过滤器或查询集)。


当前回答

你想让过滤器是动态的你就必须使用

from django.db.models import Q

brands = ['ABC','DEF' , 'GHI']

queryset = Product.objects.filter(reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]))

reduce(lambda x, y: x | y, [Q(brand=item) for items in brands])相当于

Q(brand=brands[0]) | Q(brand=brands[1]) | Q(brand=brands[2]) | .....

其他回答

有多种方法。

1. 直接使用管道|操作符。

from django.db.models import Q

Items.objects.filter(Q(field1=value) | Q(field2=value))

2. 使用__or__方法。

Items.objects.filter(Q(field1=value).__or__(field2=value))

3.通过更改默认操作。(注意重置默认行为)

Q.default = Q.OR # Not recommended (Q.AND is default behaviour)
Items.objects.filter(Q(field1=value, field2=value))
Q.default = Q.AND # Reset after use.

4. 通过使用Q类参数_connector。

logic = Q(field1=value, field2=value, field3=value, _connector=Q.OR)
Item.objects.filter(logic)

Q实现快照

class Q(tree.Node):
    """
    Encapsulate filters as objects that can then be combined logically (using
    `&` and `|`).
    """
    # Connection types
    AND = 'AND'
    OR = 'OR'
    default = AND
    conditional = True

    def __init__(self, *args, _connector=None, _negated=False, **kwargs):
        super().__init__(children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated)

    def _combine(self, other, conn):
        if not(isinstance(other, Q) or getattr(other, 'conditional', False) is True):
            raise TypeError(other)

        if not self:
            return other.copy() if hasattr(other, 'copy') else copy.copy(other)
        elif isinstance(other, Q) and not other:
            _, args, kwargs = self.deconstruct()
            return type(self)(*args, **kwargs)

        obj = type(self)()
        obj.connector = conn
        obj.add(self, conn)
        obj.add(other, conn)
        return obj

    def __or__(self, other):
        return self._combine(other, self.OR)

    def __and__(self, other):
        return self._combine(other, self.AND)
    .............

参考Q实现

Item.objects.filter(field_name__startswith='yourkeyword')

有Q个对象可以进行复杂的查找。例子:

from django.db.models import Q

Item.objects.filter(Q(creator=owner) | Q(moderated=False))

你可以使用|操作符直接组合查询集,而不需要Q对象:

result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)

(编辑-我最初不确定这是否会导致额外的查询,但@spookylukey指出,懒惰的queryset计算会照顾到这一点)

值得注意的是,可以添加Q表达式。

例如:

from django.db.models import Q

query = Q(first_name='mark')
query.add(Q(email='mark@test.com'), Q.OR)
query.add(Q(last_name='doe'), Q.AND)

queryset = User.objects.filter(query)

结果是这样的查询:

(first_name = 'mark' or email = 'mark@test.com') and last_name = 'doe'

这种方式不需要处理或运营商,减少的等。