使用Sqlite的Django:Q(...)& Q(...)与filter(...)不同.filter(...)

时间:2017-11-12 17:59:34

标签: django sqlite

my models.py:

class Words(models.Model):

    sentence = models.ForeignKey(Sentences, related_name='sentence_having_this_word')
    wordtext = models.CharField( max_length=250) # NOT UNIQUE. words written similarly can appear, as long as the sentences are different.

class Sentences(BaseModel): 
    pass

我们说我有两句话: I see a tree and a house.the tree is in front of the house.

Words包含:'I''see''a''tree''and''a',{{1 (所有这些单词使用ForeignKey到第一句话),'house''the''tree''is''in''front''of''the'(这些词与FK到第二句)。

我正在寻找在'house''tree'内部同样写出这两个单词的句子。

我做:

'house'

==> []。没有结果

但如果我这样做:  Sentences.objects.filter(Q(sentence_having_this_word__wordtext='tree')&Q(sentence_having_this_word__wordtext='house')).all()

==>我得到了预期的结果: Sentences.objects.filter(sentence_having_this_word__wordtext='tree').filter(sentence_having_this_word__wordtext='house')).all()I see a tree and a house.

我认为the tree is in front of the house.Q(...)&Q(...)是一回事吗?

编辑 filter(...).filter(...)运算符不起作用!

使用&,它正在运作......

在文档中,未提及(https://docs.djangoproject.com/en/1.7/topics/db/queries/#complex-lookups-with-q-objects

1 个答案:

答案 0 :(得分:0)

此行为记录在"Spanning multi-valued relationships"下。

当查找跨越多值关系时,例如在这种情况下反向外键,单个.filter()调用内的过滤器将过滤具有满足两个条件的单个相关对象的对象。在这种情况下,Sentence必须有一个相关的Words实例,其中wordtext等于'tree''house'。当然,这种情况永远不会成真。

当使用多个.filter()调用时,不同的对象可能与过滤器匹配。在这种情况下,Sentence必须至少有一个相关的Words实例wordtext等于'tree',并且至少有一个(但可能是不同的)Words wordtext等于'house'的实例。

and的查询按预期工作。 and是一个返回最后一个truthy值的逻辑运算符。非空的Q对象是真实的,所以:

Q(sentence_having_this_word__wordtext='tree') and Q(sentence_having_this_word__wordtext='house')

评估为:

Q(sentence_having_this_word__wordtext='house')

由于您没有包含'house'但不包含'tree'的句子,结果是相同的,但查询不是。

相关问题