简体   繁体   English

Peewee:如何从Postgres中选择数组字段为空的数据?

[英]Peewee: How to select data from Postgres where array field is empty?

Here is a simple Peewee model to work with Postgres 这是与Postgres一起使用的简单Peewee模型

import playhouse.postgres_ext as pg


db = pg.PostgresqlDatabase(""" credentials ... """)


class Artist(pg.Model):
   name = pg.TextField()
   albums = pg.ArrayField(pg.TextField, default=[])

   class Meta:
      database = db


db.create_table(Artist)
Artist.create(name='name1', albums=['album11', 'album12'])
Artist.create(name='name2')

For selecting artists with no albums the SQL query may be 对于选择没有专辑的艺术家,SQL查询可能是

>> SELECT * FROM artist WHERE albums = '{}';

 id | name  | albums 
----+-------+--------
  2 | name2 | {}

or for selecting artists with specific name 或用于选择具有特定名称的艺术家

>> SELECT * FROM artist WHERE name = 'name1';

 id | name  |      albums       
----+-------+-------------------
  1 | name1 | {album11,album12}

But when I try to achieve it with Peewee I get the following results 但是当我尝试用Peewee实现它时,我得到了以下结果

res = Artist.select().where(Artist.name == 'name1')
assert len(res) == 1 and res[0].name == 'name1'

res = Artist.select().where(Artist.albums == '{}')
assert len(res) == 0

The first query takes 'name1' as query parameter. 第一个查询将'name1'作为查询参数。

The second query takes playhouse.postgres_ext._Array object as query parameter. 第二个查询以playhouse.postgres_ext._Array对象作为查询参数。

I've looked at documentation on Postgres Extensions and did not find anything suitable. 我看了有关Postgres Extensions的文档,但没有找到合适的文档。

Could someone explain what am I doing wrong and how to select data with empty array field? 有人可以解释我在做什么错以及如何使用空数组字段选择数据吗?

You can drop into raw SQL to work around this limitation: 您可以进入原始SQL来解决此限制:

res = Artist.select().where(SQL("albums = '{}'"))
print(len(res))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM