我在閱讀this article動態生成Q對象。我的理解(大部分)問對象,但我不明白作者是如何具體是這樣做的例子:瞭解Django Q - 動態
# string representation of our queries
>>> predicates = [('question__contains', 'dinner'), ('question__contains', 'meal')]
# create the list of Q objects and run the queries as above..
>>> q_list = [Q(x) for x in predicates]
>>> Poll.objects.filter(reduce(operator.or_, q_list))
[<Poll: what shall I make for dinner>, <Poll: what is your favourite meal?>]
我特別不明白的是列表理解。 A Q
對象使用任意關鍵字參數進行格式化,如Q(question__contains='dinner')
。
如果像作者建議的那樣使用列表理解,那麼不會在每次迭代中將一個元組放入一個Q
對象中嗎?像這樣:Q(('question__contains', 'dinner'))
。
我不確定此代碼如何生成格式正確的Q
對象。
絕對真棒。非常感謝您的介紹。 – qarthandso