如何使用Django在一个查询中实现逻辑AND和OR运算符

我希望在Django查询中实现AND和OR逻辑,但是在检查了很多帖子并进行搜索后,我发现我无法在同一查询过滤器中实现AND-OR逻辑。

这是我想要实现的

我想获取具有键ABC AND值Value1或Values2 OR Values3和键CDE AND值Value4的记录

I am using python3.6, django1.11, mongoengine, and MongoDB

filter =  [ { "Key": "ABC", "Values": ["Value1", "Value2", "Value3"]}, { "Key": "CDE", "Values": ["Value4"]} ]

响应:

[  
    {
        "_id" : ObjectId("5ebd29286310619f046ba866"),
        "linked_account_id" : "135566327975",
        "payer_account_id" : "135566327975",
        "key" : "ABC",
        "Value" : "Value1"
    }

    {
        "_id" : ObjectId("5ebd29286310619f046ba866"),
        "linked_account_id" : "135566327975",
        "payer_account_id" : "135566327975",
        "key" : "ABC",
        "Value" : "Value2"
    }

    {
        "_id" : ObjectId("5ebd29286310619f046ba866"),
        "linked_account_id" : "135566327975",
        "payer_account_id" : "135566327975",
        "key" : "ABC",
        "Value" : "Value3"
    }

    {
        "_id" : ObjectId("5ebd29286310619f046ba866"),
        "linked_account_id" : "135566327975",
        "payer_account_id" : "135566327975",
        "key" : "CDE",
        "Value" : "Value4"
    }

]
评论
  • xeos
    xeos 回复

    You can use Q object, which is mentioned at docs. As an example:

    Poll.objects.get(
        Q(question__startswith='Who'),
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
    )
    

    此代码等效于:

    SELECT * from polls WHERE question LIKE 'Who%'
        AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')