[英]Operator NOT IN with Peewee
The documentation shows here how to use the IN
operator, but I couldn't find how to use the NOT IN
operator. 文档显示了如何使用IN
运算符,但我找不到如何使用NOT IN
运算符。
If I put a not <<
I get a syntax error. 如果我把一个not <<
我得到一个语法错误。
If I put a not <FieldName> <<
there is a WHERE False
instead of a subquery like WHERE (<FieldName> NOT IN (SELECT ...
. 如果我放一个not <FieldName> <<
那么有一个WHERE False
而不是像WHERE (<FieldName> NOT IN (SELECT ...
那样的子查询WHERE (<FieldName> NOT IN (SELECT ...
Here is the output with the documentation examples. 这是带有文档示例的输出。 The first one is correct, the second and third are wrong. 第一个是正确的,第二个和第三个是错误的。
>>> Tweet.select().where(Tweet.user << a_users).sql()
('SELECT t1."id", t1."user_id", t1."message", t1."created_date", t1."is_published" FROM "tweet" AS t1 WHERE (t1."user_id" IN (SELECT t2."id" FROM "user" AS t2 WHERE (Lower(Substr(t2."username", ?, ?)) = ?)))', [1, 1, 'a'])
>>> Tweet.select().where(not Tweet.user << a_users).sql()
('SELECT t1."id", t1."user_id", t1."message", t1."created_date", t1."is_published" FROM "tweet" AS t1 WHERE ?', [False])
>>> Tweet.select().where(Tweet.user not << a_users).sql()
SyntaxError: invalid syntax
Simple: 简单:
Tweet.select().where(Tweet.user.not_in(a_users))
For slightly different semantics (NOT (x in y)) as opposed to (x NOT IN y): 对于稍微不同的语义(NOT(x in y))而不是(x NOT IN y):
Tweet.select().where(~(Tweet.user << a_users))
I know that this is a "necro-posting", but this question is first hit in Google for peewee not in
query, so I would like to add it here: 我知道这是一个“死亡帖子”,但这个问题首先出现在谷歌的peewee not in
查询,所以我想在这里添加:
You can also use not_in
method which is described in the doc: 您还可以使用doc中描述的not_in
方法:
Tweet.select().where(Tweet.user.not_in(a_users))
As for me, it looks much more readable than ~ ... <<
construct. 至于我,它看起来比~ ... <<
构造更具可读性。
This has nothing to do with Peewee, really. 这与Peewee毫无关系,真的。 Peewee is using some Python operators for its own purposes. Peewee正在使用一些Python运算符来实现自己的目的。 <<
is a numeric operator normally, and it doesn't make any sense to take its logical negation. <<
通常是一个数字运算符,并且采用其逻辑否定没有任何意义。 Thus not <<
is never valid Python syntax. 因此, not <<
从来not <<
是有效的Python语法。
Your second example is close, but not
applies only to Tweet.user
( not
having higher precedence than <<
). 您的第二个示例是关闭的,但not
适用于Tweet.user
(优先级not
高于<<
)。 Add some parentheses and you get: 添加一些括号,你会得到:
Tweet.select().where(not (Tweet.user << a_users)).sql()
Now this still isn't right , as you've discovered (readers: see the comments for some discussion on this). 现在这仍然是不对的 ,正如你已经发现的那样(读者:请参阅评论以便对此进行一些讨论)。 not
returns a Boolean value, which is not what is wanted and won't work. not
返回布尔值,这不是想要的,也不会起作用。 Peewee repurposes the ~
operator for this; 为了这个,Peewee重新利用~
运算符; take a look at @coleifer's answer. 看看@ coleifer的回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.